Mysql 多个分组依据以计数最小元素?
假设在MySQL中,我有一个表Mysql 多个分组依据以计数最小元素?,mysql,sql,group-by,Mysql,Sql,Group By,假设在MySQL中,我有一个表comments,其中有字段post\u id、author\u id、date和comment 如果我想要每个帖子的第一条评论,我可以这样做 SELECT post_id, author_id, comment, MIN(date) AS comment_date FROM comments GROUP BY post_id; SELECT author_id, COUNT(*) AS total_comments FROM comments GROUP
comments
,其中有字段post\u id、author\u id、date
和comment
如果我想要每个帖子的第一条评论,我可以这样做
SELECT post_id, author_id, comment, MIN(date) AS comment_date
FROM comments
GROUP BY post_id;
SELECT author_id, COUNT(*) AS total_comments
FROM comments
GROUP BY author_id
ORDER BY total_comments DESC;
如果我想得到评论最多的作者,我可以这样做
SELECT post_id, author_id, comment, MIN(date) AS comment_date
FROM comments
GROUP BY post_id;
SELECT author_id, COUNT(*) AS total_comments
FROM comments
GROUP BY author_id
ORDER BY total_comments DESC;
我想把这些结合起来,回答“哪些作者发表了最早的评论?”这个问题,我该怎么做呢?这是一个坏SQL:
SELECT post_id, author_id, comment, MIN(date) AS comment_date
FROM comments
GROUP BY post_id;
SELECT
列和groupby
不一致。仅仅因为您的数据库恰好允许语法,并不意味着它可以满足您的需要
要回答这个问题:
“哪些作者发表了最早的评论?”
第一个查询的正确形式是:
select c.*
from comments c
where c.date = (select min(c2.date)
from comments c2
where c2.post_id = c.post_id
);
还有其他方法可以编写此逻辑,特别是使用窗口函数
那么您只需要聚合:
select author_id, count(*)
from comments c
where c.date = (select min(c2.date)
from comments c2
where c2.post_id = c.post_id
)
group by author_id
order by count(*) desc;
注:这假设最小日期确实对应于“第一条评论”,即使多个作者在同一日期发表评论