更新列a if null else更新列b else如果两列都不为null则不执行任何操作

时间:2013-05-10 01:15:09

标签: php mysql sql pdo

这是我的表: 叫做房间

+---------+---------+-----------+-------------+-------------+-------------+---------+
| room_id | room_no | room_stat | room_name   | player_a_id | player_b_id | turn_of |
+---------+---------+-----------+-------------+-------------+-------------+---------+
|       1 |       1 |         0 | blah        |           0 |           0 |       0 |
|       2 |       5 |         0 | second room |           0 |           0 |       0 |
|       3 |       3 |         0 | 3rd room    |           0 |           0 |       0 |
|       4 |       4 |         0 | 4th room    |           0 |           0 |       0 |
+---------+---------+-----------+-------------+-------------+-------------+---------+

$player_id //contains the id of the player who wants to join

#room table:

  1. 如果player_a_id!null和player_b_id!null则不更新;如果
  2. player_a_id = null和player_b_id!null然后更新房间集
  3. player_a_id = $ player_id;如果player_b_id = null且player_a_id!null则更新房间设置player_b_id = $ player_id;
  4. 我当前的查询(感谢JW)(我试图编辑它,但没有用,我失败了。)

         UPDATE  room
                 SET     player_a_id = IF(player_a_id IS NULL OR player_a_id  = 0 AND player_b_id != :chara_id, :chara_id, player_a_id),
                         player_b_id = IF(player_a_id != :chara_id AND player_b_id IS NOT NULL, :chara_id, player_b_id)
                 WHERE   room_id  = :room_id
    

    这很好,但如果两列都为空或= 0,它会更新两列;我只想更新1.

    编辑

    这是样本结果: 在player_id 1加入room_id 4之后:

    +---------+---------+-----------+-------------+-------------+-------------+---------+
    | room_id | room_no | room_stat | room_name   | player_a_id | player_b_id | turn_of |
    +---------+---------+-----------+-------------+-------------+-------------+---------+
    |       1 |       1 |         0 | blah        |           0 |           0 |       0 |
    |       2 |       5 |         0 | second room |           0 |           0 |       0 |
    |       3 |       3 |         0 | 3rd room    |           0 |           0 |       0 |
    |       4 |       4 |         0 | 4th room    |           1 |           1 |       0 |
    +---------+---------+-----------+-------------+-------------+-------------+---------+
    

    因为两列都是null,所以它更新了两列我只想更新1列。

1 个答案:

答案 0 :(得分:2)

回顾你的逻辑,你想把player_a_id更新为$ player_id IF player_a_id = 0而player_b_id不是= 0.

你想将player_b_id更新为$ player_id IF player_b_id = 0且player_a_id不是= 0.

编辑 - 如果它们都等于0,您还想更新player_a_id。

UPDATE  room
SET     player_a_id = IF(player_a_id=0, :player_id, player_a_id),
    player_b_id = IF(player_a_id!=0 AND player_b_id=0, :player_id, player_b_id)
WHERE   room_id  = :room_id