这是我的表: 叫做房间
+---------+---------+-----------+-------------+-------------+-------------+---------+
| 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:
我当前的查询(感谢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列。
答案 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