加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:36:48 所属栏目:PHP教程 来源:网络整理
导读:UPDATE userTable SET userAge=245,userName="fred" WHERE userId = 321,SET userAge=32,userName="dave" WHERE userId = 424; 有没有更好的方法来编写这段代码? 是的,使用案例陈述: UPDATE userTable SET userAge= (case when userId = 321 then 245 else
UPDATE userTable 
SET userAge=245,userName="fred"  WHERE userId = 321,SET userAge=32,userName="dave" WHERE userId = 424;

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

是的,使用案例陈述:
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);

但是,我认为更通用的方法是使用连接语法:

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 with update的强大功能.

编辑:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读