从SQLite中的特定外键中选择计数

时间:2012-02-23 15:34:55

标签: sql sqlite

我想创建一个SQL语句,告诉我有多少本书由特定作者撰写。

当您知道authorid(books表的外键)时,这很简单:

select count(*) from books where authorid = 25;
15

你可以看到id为15的作者写了15本书。是否可以为所有作者创建一个声明,使得输出如下?

author_id, author_name, number_of_books
1          Michael      15
2          Robin        7
...

3 个答案:

答案 0 :(得分:2)

您可以使用group by子句执行此操作:

select 
    a.author_id,
    a.author_name,
    count(*) as number_of_books
from
    authors a inner join
    books b on b.author_id = a.author_id
group by
    a.author_id,
    a.author_name
order by 
    number_of_books

答案 1 :(得分:2)

这将是GROUP BY查询:

select author_id, author_name, count(*) as number_of_books 
   from books
   join author on books.author_id = author.id 
   group by author_id, author_name;

答案 2 :(得分:1)

SELECT
    books.author_id, authors.author_name, COUNT(books.author_id) AS number_of_books
FROM
    authors INNER JOIN books ON books.author_id = authors.id
GROUP BY
    author_name;

另外,请确保books.author_id列不为NULL,否则性能将受到影响。