且构网

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

如何执行UPSERT,以便在更新部分中可以同时使用新值和旧值

更新时间:2023-12-06 15:27:52

正如我的评论中所述,您不必进行子选择即可引用导致ON DUPLICATE KEY触发的行.因此,在您的示例中,您可以使用以下代码:

As mentioned in my comment, you don't have to do the subselect to reference to the row that's causing ON DUPLICATE KEY to fire. So, in your example you can use the following:

INSERT INTO `item`
(`item_name`, items_in_stock)
VALUES( 'A', 27)
ON DUPLICATE KEY UPDATE
`new_items_count` = `new_items_count` + 27

请记住,大多数事情确实很简单,如果您发现过于简单的事情变得过于复杂,那么您很可能会以错误的方式进行操作:)

Remember that most things are really simple, if you catch yourself overcomplicating something that should be simple then you are most likely doing it the wrong way :)