UPDATE userTable
SET userAge=245, userName="fred" WHERE userId = 321,
SET userAge=32, userName="dave" WHERE userId = 424;
有没有更好的方法来编写此代码?
是的
,使用 case
语句:
UPDATE userTable
SET userAge= (case when userId = 321 then 245 else 32 end),
userName= (case when userId = 321 then 'fred' else 'dave' end)
WHERE userId in (321, 424);
但是,我认为更通用的编写方法是使用join
语法:
UPDATE userTable join
(select 321 as UserId, 'fred' as userName, 245 as userAge union all
select 424, 'dave', 32
) toupdate
on userTable.userId = toupdate.UserId
set userTable.userAge = toupdate.userAge,
userTable.userName = toupdate.userName;
这样可以更轻松地添加更多行,并显示将join
与update
一起使用的强大功能。
编辑:
关于性能。 两个更新需要在数据库中设置两个事务;一次更新只需要一次。 因此,一次更新可能会快一点。 仅当您没有索引时,性能差异才会明显 userTable(userId)
. 有了这样的索引,两个版本(使用 where
子句和使用 join
(都应该使用索引来查找要快速更新的行。
但是,还有一个更重要的区别。 两个更新使表在更新之间处于不一致状态 - 这些更新之间的用户 ID 和名称将不一致。 如果第二个失败或有人使用该表,他们将获得不一致的数据。 您希望同时执行两个更新(您也可以通过使用显式事务来解决此问题,但为什么要麻烦呢?
UPDATE userTable
SET userAge = case when userId = 321 then 245
when userId = 424 then 32
end,
userName = case when userId = 321 then "fred"
when userId = 424 then "dave"
end
WHERE userId in (321, 424)
一种方法是
UPDATE userTable
SET userAge=(case when userId=321 then 245 else 424 end),
userName=(case when userId=321 then 'fred' else 'dave' end)
WHERE userId in (321,, 424)
尽管使用两个查询也可以。
用例 STATMENTS。
UPDATE userTable
SET userAge = case when userId = 321 then 245
when userId = 424 then 32 end,
userName = case when userId = 321 then "fred"
when userId = 424 then "dave" end
WHERE userId in (321, 424)
我像
这样组合许多 UPDATE 查询的解决方案是插入到...在重复密钥更新时。因此,如果用户 ID 是主键,您可以使用
INSERT INTO userTable (userId, userAge, userName) VALUES
(321,245,"fred"),(424,32,"dave")
ON DUPLICATE KEY UPDATE userAge = VALUES(userAge), userName = VALUES(userName);