GROUP BY&具有多个参数的COUNT

时间:2016-10-09 07:25:51

标签: mysql sql count group-by many-to-many

我有一个简单的配置: 2个表以多对多关系链接,因此它给了我3个表。

表格作者:

idAuthor INT
name VARCHAR

表格出版物:

idPublication INT,
title VARCHAR,
date YEAR,
type VARCHAR,
conference VARCHAR,
journal VARCHAR 

表author_has_publication:

Author_idAuthor,
Publication_idPublication

我试图获得在会议SIGMOD和会议PVLDB上发表至少2篇论文的所有作者姓名。 现在我实现了这一点,但我仍然有双重结果。我的问题:

SELECT author.name, publication.journal, COUNT(*)
FROM author
INNER JOIN author_has_publication
    ON author.idAuthor = author_has_publication.Author_idAuthor
INNER JOIN publication
    ON author_has_publication.Publication_idPublication = publication.idPublication
GROUP BY publication.journal, author.name
HAVING COUNT(*) >= 2
   AND (publication.journal = 'PVLDB' OR  publication.journal = 'SIGMOD');

返回

+-------+---------+----------+
| name  | journal | COUNT(*) |
+-------+---------+----------+
| Renee | PVLDB   |        2 |
| Renee | SIGMOD  |        2 |
+-------+---------+----------+

正如你所看到的结果是正确但加倍,因为我只想要一次名字。

其他问题,如何仅为一个会议修改数字参数,例如让所有发布至少3个SIGMOD和至少1个PVLDB的作者?

1 个答案:

答案 0 :(得分:1)

如果您不关心journal,请不要选择它,它会分割您的结果。此外,普通过滤器需要放在WHERE子句中,而不是HAVING子句中:

SELECT author.name, COUNT(*)
  FROM author
 INNER JOIN author_has_publication
    ON author.idAuthor = author_has_publication.Author_idAuthor
 INNER JOIN publication
    ON author_has_publication.Publication_idPublication =
       publication.idPublication
WHERE  publication.journal IN('PVLDB','SIGMOD')       
 GROUP BY author.name
HAVING COUNT(CASE WHEN publication.journal = 'SIGMOD' THEN 1 END) >= 2
   AND COUNT(CASE WHEN publication.journal = 'PVLDB' THEN 1 END) >= 2;

对于第二个问题,请使用此HAVING()子句:

HAVING COUNT(CASE WHEN publication.journal = 'SIGMOD' THEN 1 END) >= 3
   AND COUNT(CASE WHEN publication.journal = 'PVLDB' THEN 1 END) >= 1;