2013-05-10 52 views
2

這是我的表: 稱爲房間更新一列,如果空別的更新列b,否則如果兩個列的非空奈何

+---------+---------+-----------+-------------+-------------+-------------+---------+ 
| 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表:

  1. if player_a_id!null and player_b_id!null then update nothing; if
  2. player_a_id = null and player_b_id!null then update room set
  3. player_a_id = $ player_id;如果player_b_id = null並且player_a_id!null,則更新房間設置player_b_id = $ player_id;

我目前的查詢(謝謝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 | 
+---------+---------+-----------+-------------+-------------+-------------+---------+ 

因爲這兩個字段爲空,然後它會同時更新的列我只想更新1列。

+0

你能提供一些樣本數據和結果嗎?這將有助於澄清你的規則。 – 2013-05-10 01:19:43

+0

鑑於您的編輯,您更新的玩家是否都是0(均爲空)? – sgeddes 2013-05-10 01:35:43

回答

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

編輯 - 你也想更新player_a_id如果兩者都等於0

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 
+0

@sgeddess是的,但是再次說明的是,當player_a_id和player_b_id都爲null時,我想在player_a_id上插入player_id,你的查詢將會起作用,但是隻有當一名玩家已經在房間中時,它纔會起作用。如果你幫助我,我會真正appriciate它。 – Viscocent 2013-05-10 01:38:50

+0

@Viscocent - 爲什麼不把第一個IF語句改成player_a_id = 0 - 這應該涵蓋兩種情況? – sgeddes 2013-05-10 01:44:13

+0

我已經明白了。只是在#1'player_b_id!=:chara_id'上添加了這個條件,並且如果#2'player_a_id!=:chara_id' – Viscocent 2013-05-10 01:57:13

相關問題