SQL选择列取决于另一列的值

时间:2015-01-15 19:31:39

标签: sql select

请考虑下表。

-----------------------------------------------------
| game_id | blue_player_id | red_player_id | turn_of |
-----------------------------------------------------
|    1    |        4       |        5      |  "blue" |
-----------------------------------------------------
|    2    |        1       |        2      |  "red"  |
-----------------------------------------------------
|    3    |        3       |        4      |  "blue" |
-----------------------------------------------------

我想编写一个查询,根据给定游戏ID的turn_of列选择blue_player_id或red_player_id。

因此,对于game_id = 1,它应该返回4,对于game_id = 2,它应该返回2,而对于game_id = 3,它应该返回3.

我知道我可以在两个查询中执行此操作,首先选择它是谁,然后在第二个查询中选择右列。但是,是否存在一种不使用特定于数据库的SQL的查询方法?

3 个答案:

答案 0 :(得分:2)

select gameId,
       case when turn_of = 'blue' 
       then blue_player_id 
       else red_player_id 
       end as PlayerID
from MYTable

答案 1 :(得分:1)

SELECT
    game_id,
    CASE turn_of
       WHEN 'blue' THEN blue_player_id
       WHEN 'red'  THEN red_player_id 
       ELSE null
    END as PlayerId
FROM table

答案 2 :(得分:1)

如果是SQL,可以使用CASE语句。

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
   WHEN <othervalue> THEN <returnthis>
   ELSE <returndefaultcase>
   END as something
FROM <table>

你需要这样的东西

SELECT CASE WHEN turn_of='blue'
then blue_player_id else red_player_id 
end as player_id 
FROM Your_TABLE 
WHERE game_id = 0