mySQL匹配日期,并在连接时返回null

时间:2018-10-22 23:50:58

标签: mysql sql

我正在尝试结合一些NBA数据,盒子得分和高级球员统计数据。我目前遇到的查询是:

select boxes.GNO, boxes.NAME, boxes.DATE, advstat.YEAR, advstat.NAME, advstat.AGE
from boxes left join advstat on boxes.NAME=advstat.NAME
group by boxes.NAME, boxes.GNO having boxes.GNO = 1;

boxes.GNO = 1只是为了限制此时返回的数据,最终我将返回boxs表中所有游戏的数据。

通过上面的查询,我得到以下输出:

+------+------------------+------------+------+------------------+------+
| GNO  | NAME             | DATE       | YEAR | NAME             | AGE  |
+------+------------------+------------+------+------------------+------+
|    1 | Al Horford       | 2017-10-17 | 2008 | Al Horford       |   21 |
|    1 | Aron Baynes      | 2017-10-17 | 2013 | Aron Baynes      |   26 |
|    1 | Derrick Rose     | 2017-10-17 | 2009 | Derrick Rose     |   20 |
|    1 | Dwyane Wade      | 2017-10-17 | 2004 | Dwyane Wade      |   22 |
|    1 | Gordon Hayward   | 2017-10-17 | 2011 | Gordon Hayward   |   20 |
|    1 | Iman Shumpert    | 2017-10-17 | 2012 | Iman Shumpert    |   21 |
|    1 | Jae Crowder      | 2017-10-17 | 2013 | Jae Crowder      |   22 |
|    1 | Jaylen Brown     | 2017-10-17 | 2017 | Jaylen Brown     |   20 |
|    1 | Jayson Tatum     | 2017-10-17 | NULL | NULL             | NULL |
|    1 | Jeff Green       | 2017-10-17 | 2008 | Jeff Green       |   21 |
|    1 | JR Smith         | 2017-10-17 | NULL | NULL             | NULL |
|    1 | Kevin Love       | 2017-10-17 | 2009 | Kevin Love       |   20 |
|    1 | Kyle Korver      | 2017-10-17 | 2004 | Kyle Korver      |   22 |
|    1 | Kyrie Irving     | 2017-10-17 | 2012 | Kyrie Irving     |   19 |
|    1 | LeBron James     | 2017-10-17 | 2004 | LeBron James     |   19 |
|    1 | Marcus Smart     | 2017-10-17 | 2015 | Marcus Smart     |   20 |
|    1 | Semi Ojeleye     | 2017-10-17 | NULL | NULL             | NULL |
|    1 | Shane Larkin     | 2017-10-17 | 2014 | Shane Larkin     |   21 |
|    1 | Terry Rozier     | 2017-10-17 | 2016 | Terry Rozier     |   21 |
|    1 | Tristan Thompson | 2017-10-17 | 2012 | Tristan Thompson |   20 |
+------+------------------+------------+------+------------------+------+

这几乎是正确的。但是我需要advstat.YEAR来匹配year(boxes.DATE)。如果我添加.. 其中year(boxes.DATE)= advstat.YEAR,排除了NULL数据,这不是我想要的。我需要这张表看起来像上面的样子,只是年份正确地排列在两张桌子之间。

任何帮助将不胜感激!干杯!

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

select b.GNO, b.NAME, b.DATE, s.YEAR, s.NAME, s.AGE
from boxes b left join
     advstat s
     on b.NAME = s.NAME and year(b.date) = s.year
where b.GNO = 1
group by b.NAME, b.GNO ;

请注意,在group by之前进行过滤通常会更有效,因此我建议使用where而不是having