假设我有一个这样的数据库设置,我想通过将优先级更改为最后一个数字+ 1来将Milk移到最后。
id | item | priority ---|------|---------- [...] 26 | Milk | 1 27 | Eggs | 2 28 | Ham | 3
所以我需要运行这样的东西
UPDATE shopping SET priority = (SELECT priority FROM shopping ORDER BY priority DESC LIMIT 1) + 1 WHERE id = '26'
并最终得到类似的东西
id | item | priority ---|------|---------- [...] 27 | Eggs | 2 28 | Ham | 3 26 | Milk | 4
如何正确地执行 ?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
您的请求可能是:
UPDATE shopping SET priority = (select max(priority)+1) where id=26;
但这不起作用,您必须对请求,来源和详细信息进行相同的更改:
http://the-stickman.com/uncategorized/mysql-update-with-select-on-the-same-table-in-the-same-query/