我有两张桌子:
每位作家都有她写的书籍清单。我想让所有作家都知道他们每人写的书数。 有没有办法在一个查询中执行此操作?
答案 0 :(得分:0)
我相信这对你有用。不确定是否有更有效的方法:
select id, (select count(*) from books where books.writer_id = writers.id ) count from writers
答案 1 :(得分:0)
我更喜欢以下非嵌套版本:
SELECT
writers.id,
writers.name,
count(books.*) as BookCount
FROM
writers
LEFT JOIN books ON writers.id = books.writer_id
GROUP BY
writers.id,
writers.name