UPDATE some_table set rank=1 WHERE id=25
UPDATE some_table set rank=2 WHERE id=15
UPDATE some_table set rank=3 WHERE id=10
UPDATE some_table set rank=4 WHERE id=12
UPDATE some_table set rank=5 WHERE id=13
UPDATE some_table set rank=6 WHERE id=14
UPDATE some_table set rank=7 WHERE id=11
如何将其转换为单个查询,因为我想不到一个? id
的这些值是按顺序排列的。想象一下有图像的照片库,用户可以选择重新排列这些图像的序列。后端将根据用户定义的序列分配排名,并将在ORDER BY子句中使用。
答案 0 :(得分:8)
update some_table
set rank = case
when id = 25 then 1
when id = 15 then 2
when id = 10 then 3
when id = 12 then 4
when id = 13 then 5
when id = 14 then 6
when id = 11 then 7
end
答案 1 :(得分:2)
您可以使用案例结构......与此相似..
CASE id1
WHEN id = 25 THEN UPDATE some_table SET rank = 1
ELSE
WHEN id = 15 THEN UPDATE some_table SET rank = 2
ELSE
etc...
END CASE
参考:
DELIMITER |
CREATE PROCEDURE p()
BEGIN
DECLARE v INT DEFAULT 1;
CASE v
WHEN 2 THEN SELECT v;
WHEN 3 THEN SELECT 0;
ELSE
BEGIN
END;
END CASE;
END;
|