使用日期部分日期字段

时间:2015-05-21 04:54:51

标签: mysql

我有3张桌子:

events (id, event_date, type)

champions (id, year, player_id, type)

players (id, fname, lname)

我想创建一个包含2列的图表。一个列出events表或champions表中存在的每年(没有重复)的一个。另一个列出给定年份的冠军名称(如果存在)。我只想包含事件类型为night的行。

所以输出可能如下所示:

|Year|Champion|

|2015|  (empty)      |   <---- no champion defined for 2015 yet, so column is empty

|2014|  David Smith|  <--- no events in the database for 2014, but a champion is defined, so he shows up in column

|2012|  Jimmy Garland|

(2013年没有任何活动或冠军,因此会跳过该行。)

我尝试了这个查询,但它最终给了我2014年的2行。其中一个空第二列,另一个在第二列有一个冠军。

SELECT DISTINCT EXTRACT(YEAR FROM events.event_date) AS evyear, champions.*, players.*
FROM events 
LEFT JOIN champions ON EXTRACT(YEAR FROM events.event_date)=champions.year
    LEFT OUTER JOIN players ON champions.player_id=players.id AND champions.type = 'night'
WHERE events.type = 'night'
ORDER BY evyear DESC

1 个答案:

答案 0 :(得分:0)

您希望走在正确的轨道上,但您需要从子查询中获取所有活动年份。

select q.`year`, coalesce(concat(p.fname, ' ', p.lname), 'No Champion') champion from (
  select distinct year(event_date) `year`
    from events
  ) q
  left join champions c
    on q.`year` = c.`year` and c.type = 'night'
  left join players p
    on c.player_id = p.id

small demo here