3

このようにデータベースが設定されているとしましょう。優先順位を最後の数字 + 1 に変更して、Milk を最後に移動したいとします。

ID | アイテム | 優先順位
---|------|----------   
[...]
26 | ミルク | 1
27 | 卵 | 卵 2
28 | ハム | ハム | 3

だから私はこのようなものを実行する必要があります

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

そして、このようなもので終わります

ID | アイテム | 優先順位
---|------|----------   
[...]
27 | 卵 | 卵 2
28 | ハム | ハム | 3
26 | ミルク | 4

これを正しく行うにはどうすればよいですか?

4

2 に答える 2

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
于 2012-09-28T15:35:14.670 に答える
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/

于 2012-09-28T16:40:50.833 に答える