这个问题在这里已有答案:
假设我有一个包含2个表的数据库:author和book。
mysql>
mysql> CREATE TABLE author
-> (
-> a_id INT UNSIGNED NOT NULL AUTO_INCREMENT, # author ID
-> name VARCHAR(30) NOT NULL, # author name
-> PRIMARY KEY (a_id),
-> UNIQUE (name)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE book
-> (
-> a_id INT UNSIGNED NOT NULL, # author ID
-> p_id INT UNSIGNED NOT NULL AUTO_INCREMENT, # book ID
-> title VARCHAR(100) NOT NULL, # title of book
-> state VARCHAR(2) NOT NULL, # state where purchased
-> price INT UNSIGNED, # purchase price (dollars)
-> INDEX (a_id),
-> PRIMARY KEY (p_id)
-> );
Query OK, 0 rows affected (0.01 sec)
如何查找到目前为止还没有出版过一本书的作者数量?
使用此选项来计算没有出版书籍的作者:
SELECT COUNT(1)
FROM author AS a
LEFT JOIN book AS b ON a.a_id = b.a_id
WHERE b.p_id IS NULL
使用
SELECT a.a_id, a.name
获取没有出版书籍的作者名单。
这是家庭作业吗?你应该告诉我们你尝试了什么?那说,这很容易:
SELECT Count(*) FROM author a
WHERE NOT EXISTS (SELECT 1 FROM book b WHERE b.a_id = a.a_id)
您可以使用子查询和计数来从书表中获取唯一作者的数量,并使用NOT IN
和作者表来获取未编写书籍的作者
SELECT COUNT(a.a_id) as author_count
FROM author as a
WHERE a.a_id NOT IN (SELECT DISTINCT b.a_id FROM book as b)