sql使用count with group by和having

时间:2013-06-30 14:03:17

标签: mysql sql

在编写涉及聚合函数的查询时(例如Count和使用Having时)我遇到了麻烦。我有两个People(id和name)和Books(bookid,author_id,title)表(这里author_id是People id的外键)。 我目前有一个查询,回复给我所有写过书的人(不是所有人都写过书)。

SELECT People.name, 
       Books.title 
FROM People, 
     Books 
WHERE Books.author_id = People.id;

现在我试图找到只写了2本以上书并且选择相同信息(people.name和books.title)的人,但我对如何解决这个问题感到困惑。我一直在尝试使用HAVING计数(People.name)> 1但我得到的选择绝对不正确。

使用sql的新功能,尤其是在我的查询中添加这些额外参数时,我们只是想知道是否有人可以帮助我。我还没有看到任何有这些条件的查询示例。

2 个答案:

答案 0 :(得分:3)

最好以这种方式加入你的桌子:

SELECT People.name, Books.title
FROM People INNER JOIN Books ON Books.author_id = People.id;

你可以添加你的HAVING子句:

SELECT Books.author_id
FROM Books
GROUP BY Books.author_id
HAVING COUNT(*)>=2

然后选择您需要的所有信息,您可以使用:

SELECT People.name, Books.title
FROM People INNER JOIN Books ON Books.author_id = People.id
WHERE People.ID IN (
  SELECT Books.author_id
  FROM Books
  GROUP BY Books.author_id
  HAVING COUNT(*)>=2
)

答案 1 :(得分:2)

SELECT People.name, 
       Books.title 
FROM People, 
     Books 
WHERE Books.author_id = People.id 
  and exists (select 1 
              from (
                 SELECT People.name name 
                 FROM People, 
                      Books 
                 WHERE Books.author_id = People.id 
                 group by Pepole.name 
                 having count(People.name)>1
              ) temp 
              where temp.name = People.name)