这可以作为单个更新查询运行吗?

时间:2013-08-06 13:50:11

标签: php mysql sql

UPDATE userTable 
SET userAge=245, userName="fred"  WHERE userId = 321, 
SET userAge=32, userName="dave" WHERE userId = 424;

有没有更好的方法来编写此代码?

5 个答案:

答案 0 :(得分:8)

是的,使用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;

这样可以更轻松地添加更多行,并显示joinupdate一起使用的效果。

编辑:

关于表现。两个更新需要在数据库中设置两个事务;一次更新只需要一次。因此,一次更新可能会更快一点。只有在userTable(userId)上有 no 索引时,性能差异才会明显。使用这样的索引,两个版本(使用where子句并使用join)应该使用索引来查找要快速更新的行。

但是,有一个更重要的区别。两次更新使表在更新之间处于不一致状态 - 用户ID和名称在这些更新之间不一致。如果第二个失败或有人使用该表,它们将具有不一致的数据。您希望同时执行这两个更新(您也可以通过使用显式事务来解决此问题,但为什么要这么麻烦?)。

答案 1 :(得分:5)

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) 

答案 2 :(得分:2)

这样做的一种方法是

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)

尽管使用两个查询进行此操作也没问题。

答案 3 :(得分:2)

使用案例STATEMENTS。

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) 

答案 4 :(得分:2)

我将这样的UPDATE查询组合起来的解决方案是INSERT INTO ... ON DUPLICATE KEY UPDATE。因此,如果userId是主键,则可以使用

INSERT INTO userTable (userId, userAge, userName) VALUES
(321,245,"fred"),(424,32,"dave")
ON DUPLICATE KEY UPDATE userAge = VALUES(userAge), userName = VALUES(userName);
相关问题