mysql - 在一次 SQL 查询中为多行更新多列

标签 mysql sql database database-design

我试图在一个查询中为多行设置多个列,但到目前为止没有运气。

这是我的 table 的样子

表:用户

enter image description here

我想在 user_id IN (3,4,5) 上设置“ext_id”,还想在同一行上设置 ext_flag = Y 和 admin_role = admin。

结果表如下所示 enter image description here

我的查询看起来像这样,但由于不熟悉 SQL 语法而出现错误。

update user
set ext_flag = 'Y', admin_role = 'admin', ext_id = 
case 
when user_id = 2 then 345
when user_id = 4 then 456
when user_id = 5 then 789
end

我在使用多列的 SET 语法时遇到了困难。

最佳答案

试试这个

 update user
 set ext_flag = 'Y', admin_role = 'admin', ext_id = 
 case 
 when user_id = 2 then 345
 when user_id = 4 then 456
 when user_id = 5 then 789
 end
 **WHERE user_id  in (2,4,5)**

关于mysql - 在一次 SQL 查询中为多行更新多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091318/

相关文章:

php - 形式安全。 PHP MySQL

php - 从 MySql 数据库中获取值到表单中

php多表更改

mysql - SQL(通过 phpMyAdmin)

php - 从数据库到可编辑形式的数组

database - Postgres : Dump schema-only but leave data intact for a few tables

php - 异常 'PDOException',消息为“SQLSTATE[HY093] : Invalid parameter number: number of bound variables does not match number of tokens”

php - 在基于WEB的应用程序中使用PHP进行MY SQL数据库连接

mysql - 使用 Case When 语句查询获取 2 个不同条件下的 Id 计数

java - JTable 过滤数据无法正常工作