表格 - 图库
+----+----------+------------+----------+
| id | user_id | is_primary | photo |
+----+----------+------------+----------+
| 1 | 1 | 1 | img1.jpg |
| 2 | 2 | 1 | img2.jpg |
| 3 | 1 | 0 | img3.jpg |
| 4 | 1 | 0 | img4.jpg |
| 5 | 1 | 0 | img5.jpg |
| 6 | 3 | 1 | img6.jpg |
| 7 | 2 | 0 | img7.jpg |
+----+----------+------------+----------+
UPDATE galleries set is_primary=0 WHERE user_id=1
UPDATE galleries set is_primary=1 WHERE id=4
有一个列名 is_primary
我只需要设置 1 行 is_primary=1
which user id 1
但是已经有一行is_primary = 1 and user_id=1
我想在更新之前更新 is_primary=1
which id=4
我需要设置所有 is_primary=0
which user_id =1
。
我不想为更新写 2 次查询。
如何编写嵌套查询来更新我的记录?
最佳答案
你可以使用case-when
something as
update galleries
set is_primary =
case
when id=4 then 1 else 0
end
where user_id = 1 ;
关于mysql - 嵌套更新的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30569451/