如何查找未出版书籍的作者人数

时间:2019-04-13 10:20:00

标签: mysql sql

假设我有一个包含2个表的数据库:作者和书。

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)

如何查找到现在为止还没有出版过一本书的作者数量?

3 个答案:

答案 0 :(得分:1)

使用此选择对没有出版任何书籍的作者进行计数:

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

获取未出版书籍的作者列表。

答案 1 :(得分:1)

这是家庭作业吗?您真的应该告诉我们您尝试了什么?也就是说,这很简单:

SELECT Count(*) FROM author a
WHERE NOT EXISTS (SELECT 1 FROM book b WHERE b.a_id = a.a_id)

答案 2 :(得分:0)

您可以使用子查询和计数来从书本表中获取唯一作者的数量,并使用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)