且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

首先更新或删除,然后插入

更新时间:2023-12-04 16:17:55

如果每部电话的功能数量会发生变化,则必须删除并插入.要更新,您需要:

If the number of features per phone will ever change, then you must delete and insert. To update, you'd need to:

  • 获取当前功能集
  • 弄清楚有什么不同,添加了什么以及删除了什么
  • 运行查询以更新,插入新数据和删除旧数据.

就好像您只是删除整个列表并重新插入它们一样,您可以避免一些维护上的麻烦.

Where as if you just delete the whole list and re-insert them, you save yourself some maintenance headaches.

如果数据一致性是一个问题或关注点(数据已删除但在插入之前发生错误导致脚本无法完成),则将查询包装在事务中.

If consistency of your data is an issue or concern (the data is deleted but an error happens before insert causing the script to not complete) then wrap your queries in a transaction.

以这个例子为例:

我有一个包含Posts(id, title, body)Categories(id, post_id, category)的博客.我的第一篇文章"Hello World"被归类为元,PHP和javascript".然后一年后,我修改了帖子,以获取有关mysql的一些信息(或添加mysql类别)并删除javascript.

I have a blog with Posts(id, title, body) and Categories(id, post_id, category). My first Post, "Hello World" is categorized under "meta, php, and javascript". Then a year later, I revise the post to have some information about mysql (or I add a mysql category) and take out javascript.

这是我需要做的(主要是伪代码):

Here's what I'd need to do (mostly psuedocode):

//old set
SELECT * FROM Categories WHERE post_id=1

foreach($categories as $category) {
    if(in_array($category['id'], $_POST['categories']) {
        //this category is in the new set and the old set, do nothing
    }
    elseif(!in_array($category['id'], $_POST['categories']) {
        //this category is in the old set, but not the new one, delete it
        $queries[] = "DELETE FROM Categories WHERE id=".$category['id'];
    }
    else {
        //new category, add it
        $queries[] = "INSERT INTO Categories()..."
    }
}

foreach($queries as $item) {
    //run query
}

相对于此:

DELETE FROM Categories WHERE post_id=$_POST['id']

foreach($_POST['categories'] as $item) {
    INSERT INTO Categories() ...
}

我个人认为选项2更好.

Personally, I think option #2 is better.