0

我有两个表用于书籍数据库,定义如下:

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)

在此先感谢您的帮助,希望我足够清楚。

4

1 回答 1

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

对于带有空格的列别名,反引号起作用。

于 2013-02-19T05:50:30.483 回答