更新列的值(如果为空)或“0”否则更新同一表中的其他列

时间:2013-05-09 06:17:38

标签: php mysql sql pdo

我想更新我的列player_a_id,如果它是空的,否则更新player_b_id。

这是我的表:     的

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

基本上我的目标很简单,当玩家加入房间时它更新了player_a_id,否则如果player_a_id已经被占用,那么更新player_b_id。

1 个答案:

答案 0 :(得分:2)

如果术语empty表示NULL

UPDATE  room
SET     player_a_id = IF(player_a_id IS NULL OR player_a_id = 0, yourVal, player_a_id),
        player_b_id = IF(player_a_id IS NOT NULL OR player_a_id <> 0, yourVal, player_b_id)
WHERE   room_no  = '' // <<== (sample only) set your condition here....