根据MYSQL中的字段值选择列

时间:2013-07-01 14:34:19

标签: mysql database

我需要根据不同字段中的值从数据库中选择不同的列。

玩家:

ID     EVENT_ID     NAME   TEAM  
--------------------------------
1         1         Ann      1
2         1         Bob      2
3         2         Claire   1

活动:

ID     EVENT_NAME     TEAM_1       TEAM_2    
----------------------------------------------
1      Football       All Stars    Tornadoes   
2      Tennis         Dynamos      Best Team  

根据我的表格,我希望能够搜索玩家ID 2,并根据players.team值获取他们的团队名称。 所以像这样:

SELECT players.*,
(SELECT team+"players.team" AS team_name FROM events WHERE players.event_id = events.id)
WHERE players.id = '2'

得到结果:

Player.ID:   1
Player.Name: Bob
Team_Name:   Tornadoes

2 个答案:

答案 0 :(得分:1)

SELECT p.id,p.name, IF(p.team = 1,e.team_1,e.team_2)
FROM players p
LEFT JOIN events e ON (p.event_id = e.id)
WHERE p.id = 2;

答案 1 :(得分:1)

您可以使用CASE

    SELECT p.id, p.name, 
           CASE WHEN p.team = 1 THEN e.team_1 ELSE e.team_2 END AS Team_Name 
      FROM Players p 
 LEFT JOIN Events e 
        ON e.id = p.event_id 
     WHERE p.id = 2