• 请不要在回答技术问题时复制粘贴 AI 生成的内容
schezuk
V2EX  ›  程序员

MYSQL 中,把 select 和 update 两个相关语句,捏成一个 update 语句,是良好做法吗?

  •  
  •   schezuk · Apr 1, 2015 · 4064 views
    This topic created in 4062 days ago, the information mentioned may be changed or developed.
    一个表,主键`id` 列`content` 列`pwd`
    当密码(`pwd`)符合数据库记载,则允许修改`content`
    那么下面两个方式哪一个是良好的做法?

    --------
    1. 分成两句sql,先查后改
      select * where id=12345
    php对返回的这一行数据,根据pwd字段判断是否继续执行下一条sql
      update set …… where id=12345

    --------
    2. 是单一sql语句,捏在一起
      update set …… where id=12345 and pwd='password'
    根据影响了1行还是0行判断执行成功与否

    --------
    3. 请问,我要在php中prepare并执行下面语句
      update set `content`=:content where id=12345
    在php中怎么修改该语句,使得当
      empty($array[':content'])===true
    时,`content`字段不被修改?
    bravejoe
        1
    bravejoe  
       Apr 1, 2015 via iPad
    如果你的代码逻辑需要在查询后做一些业务处理然后再update,可以先查再写,注意需要用锁,悲观锁乐观锁都可以,防止并发;
    如果仅仅为了更新,一次update判断成功条数就够,节约一次查询;

    content为空时不更新,最好分成两条不同的sql;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1519 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 16:46 · PVG 00:46 · LAX 09:46 · JFK 12:46
    ♥ Do have faith in what you're doing.