查询中的多个查找可能有NULL值

时间:2016-10-16 17:51:41

标签: mysql

这是我拥有的,也是我想要完成的事情:

clock_gettime(3)

这是我当前的MYSQL查询:

teams TABLE
TeamID Season     Coach1     Coach2
1      2011       35         22
2      2011       27
3      2012       11
4      2013       22         13

staff TABLE
StaffID     Nickname
11          Bob
13          Rick
22          Mary
27          Steve
35          Joe

desired OUTPUT:
TeamID Season   c1       c2
1      2011     Joe      Mary
2      2011     Steve
3      2012     Bob
4      2013     Mary     Rick

返回:

SELECT gt.TeamID, gt.Season, gt.Coach1, c1.Nickname c1Nickname, gt.Coach2, c2.Nickname c2Nickname
FROM gladiator_teams as gt, staff as c1, staff as c2
WHERE gt.Coach1=c1.StaffID AND gt.Coach2=c2.StaffID

我无法弄清楚如何修改查询以返回Coach 2具有NULL值的行。我想我需要一个IFNULL函数去某个地方,但我无法确定究竟在哪里。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你应该使用左JOIN

SELECT 
   gt.TeamID
 , gt.Season
 , gt.Coach1
 , c1.Nickname c1Nickname
 , gt.Coach2
 , c2.Nickname c2Nickname
FROM gladiator_teams as gt
LEFT JOIN staff as c1  gt.Coach1=c1.StaffID
LEFT JOIN staff as c2 gt.Coach2=c2.StaffID