从连接表中按年查询数据

时间:2017-03-11 18:28:29

标签: mysql sql database

我有一个名为colors的表,我需要创建一个查询,根据我的另一个表programs中的日期,返回每年使用的唯一颜色数。 它看起来像这样:

colors
+----+----------+
| id |   name   |
+----+----------+
|  1 | blue     |
|  2 | yellow   |
+----+----------+

programs
+----+------------+
| id |    date    |
+----+------------+
|  1 | 2016-01-08 |
|  2 | 2016-02-08 |
|  3 | 2017-02-08 |
+----+------------+

programs_colors
+------------+----------+
| program_id | color_id |
+------------+----------+
|          1 |        1 |
|          1 |        1 |
|          2 |        2 |
|          2 |        1 |
|          3 |        1 |
|          3 |        1 |
+------------+----------+

我试过这个:

SELECT min(date), count(*) FROM (
  SELECT min(date) AS date FROM programs_colors INNER JOIN programs ON programs.id = program_id GROUP BY color_id
) AS a GROUP BY year(date)

min(date):      count(*):
2016-01-08      2
2017-01-08      0

但是上面的查询将我的颜色整体分组,但我需要按年份分组

预期结果:

min(date):      count(*):
2016-01-08      2
2017-01-08      1

我希望我的问题有道理

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你可能需要做这样的事情

SELECT min(date), sum(count) FROM (
  SELECT min(date) AS date, count(*) as count FROM programs_colors INNER JOIN programs ON programs.id = program_id GROUP BY color_id
) AS a GROUP BY year(date)

答案 1 :(得分:1)

SELECT  min(date), count(distinct color_id) 
FROM    programs_colors 
INNER   JOIN programs 
ON      programs.id = program_id 
GROUP   BY year(date);