SQL通过COUNT()列限制输出

时间:2013-02-19 05:47:21

标签: mysql

我有一个图书数据库的两个表,定义如下:

CREATE TABLE Publisher(
   PublisherID INT,
   Name VARCHAR(50) NOT NULL,
   City VARCHAR(30),
   StateCode CHAR(2),
   constraint publisher_publisherID_pk PRIMARY KEY (publisherID),
   constraint publisher_statecode_fk FOREIGN KEY (StateCode) REFERENCES State(StateCode)
 );

CREATE TABLE Book(
   ISBN        CHAR(13),
   Title       VARCHAR(70) NOT NULL,
   Description VARCHAR(100),
   Category    INT,
   Edition     CHAR(30),
   PublisherID INT         NOT NULL,
   constraint book_ISBN_pk PRIMARY KEY (ISBN),
   constraint book_category_fk FOREIGN KEY (Category) REFERENCES Category(CatID),
   constraint book_publisherID_fk FOREIGN KEY (PublisherID) REFERENCES Publisher(PublisherID)
);

我想显示为发布商名称中“已阅读”且已发布超过两本图书的发布商发布的出版商名称和图书数量。

到目前为止,我有这个:

SELECT Publisher.Name AS 'Publisher Name', COUNT(*) AS 'Book Count' 
FROM Book 
LEFT JOIN Publisher USING (PublisherID) 
WHERE Publisher.Name LIKE '%read%' 
GROUP BY Publisher.Name;

但是不知道如何将结果限制为返回true的所有结果。我不能让LIMIT工作,我不确定在这里使用它是否正确。我也不确定如何参考'Book Count'(列名必须是这个)。仅搜索Google会返回限制行数(类似搜索词)。

我目前的输出是:

+----------------------------------+------------+
| Publisher Name                   | Book Count |
+----------------------------------+------------+
| EZRead Masterpiece Comics        |          3 |
| ReadEmandWeep Romance Publishing |          5 |
| ReadMeFirst House of Publishing  |          2 |
| ReadMeNext House of Publishing   |          2 |
+----------------------------------+------------+
4 rows in set (0.00 sec)

但我想要这个:

+----------------------------------+------------+
| Publisher Name                   | Book Count |
+----------------------------------+------------+
| EZRead Masterpiece Comics        |          3 |
| ReadEmandWeep Romance Publishing |          5 |
+----------------------------------+------------+
2 rows in set (0.00 sec)

提前感谢您的帮助,希望我已经足够清楚了。

1 个答案:

答案 0 :(得分:1)

你快到了。

SELECT Publisher.Name AS 'Publisher Name', COUNT(*) AS 'Book Count' 
FROM Book 
LEFT JOIN Publisher USING (PublisherID)
WHERE Publisher.Name LIKE '%read%' 
GROUP BY Publisher.Name
HAVING `Book Count` > 2        ## Notice the HAVING clause?;

修改

忘记HAVING必须在GROUP BY之后。

编辑2

对于带空格的列别名,反引号可以正常工作。