这是我想要做的一个例子:
我必须按月/年组织一系列事件,包括事件的数量,然后是这些事件的ID的逗号列表。
这就是我所拥有的:
SELECT count(*) as counter,
MONTHNAME(publishDate) as month,
YEAR(publishDate) as year
FROM bursch.events
GROUP BY YEAR(publishDate),
MONTH(publishDate)
order by year desc;
但是,我也需要那些ID(2,5,6)<<<像这样:
这是概念:
SELECT count(*) as counter,
MONTHNAME(publishDate) as month,
YEAR(publishDate) as year,
(select id
from events
where 'call conditions affect the main query') as IDList
FROM events
GROUP BY YEAR(publishDate),
MONTH(publishDate)
order by year desc;
这会导致类似这样的事情:
counter | month | year | ids
-----------------------------------------
3 | June | 2013 | 45,49,50
4 | July | 2013 | 39,40,41,42
2 | March | 2011 | 33,34
5 | May | 2011 | 27,29,30,31,32
1 | June | 2011 | 22
4 | July | 2011 | 14,17,18,19
1 | January | 2010 | 13
我可以将我的选择结果基于主select语句的条件。可能有更好的方法来获得此结果。也许是一种更简单的方法。但是选择为字段部分。会叫什么?相关查询?不确定。我已经看到我可以在Oracle和MySQL中做到这一点并且它派上用场(如果我只知道它叫什么)。
先谢谢了。如果有什么不清楚,请告诉我。
答案 0 :(得分:2)
MySQL有一个名为GROUP_CONCAT()的函数,它连接行而不是列。
SELECT COUNT(*) as counter,
MONTHNAME(publishDate) as month,
YEAR(publishDate) as year,
GROUP_CONCAT(id) as IDs
FROM events
GROUP BY YEAR(publishDate),
MONTH(publishDate)
ORDER BY year desc;