gpt4 book ai didi

mysql - 用另一个查询结果更新行

转载 作者:行者123 更新时间:2023-11-29 01:04:09 25 4
gpt4 key购买 nike

假设我有一个这样设置的数据库,我想通过将优先级更改为最后一个数字 + 1 来将 Milk 移到最后。

id | item | priority---|------|----------   [...]26 | Milk | 127 | Eggs | 228 | Ham  | 3

So I need to run something like this

UPDATE shopping SET priority = (SELECT priority FROM shopping ORDER BY priority DESC LIMIT 1) + 1 WHERE id = '26'

最后得到这样的结果

id | item | priority---|------|----------   [...]27 | Eggs | 228 | Ham  | 326 | Milk | 4

我如何正确地执行此操作?

最佳答案

UPDATE `shopping` s, (
SELECT
MAX(`priority`) AS 'maxPriority',
MAX(`id`) AS 'maxId'
FROM `shopping`
) t
SET
s.`priority` = t.`maxPriority` + 1,
s.`id` = t.`maxId` + 1
WHERE s.`id`=26
AND s.`priority` != t.`maxPriority`
# this ensures that it's not the one that's
# already holding the max priority

关于mysql - 用另一个查询结果更新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com