mysql - 嵌套更新的 MySQL 查询

标签 mysql

表格 - 图库

+----+----------+------------+----------+
| 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/

相关文章:

mysql - SQL批量插入CSV语法错误?

mysql从每组中获取最后10条记录

php - Laravel 查询 - 从相关表中获取对象及其计数

php - MYSQL 查询仅在不是特定日期时进行分组

mysql - 在mysql的select查询中编写last()函数

javascript - 如何从mysql获取id到模态?

php - table_exists() 方法可能无法正常工作

mysql - 在 mysql select 期间添加列

mysql - 插入变量和常量标记的表串联

php - 分离多个不同日期范围内的结果