如何计算表中每个外键ID的实例数量?
这是我简单的SQL问题
我有两个表格:
图书
------------------------------------------------------- | book_id | author | genre | price | publication_date | -------------------------------------------------------
命令
------------------------------------ | order_id | customer_id | book_id | ------------------------------------
我想创build一个查询返回:
-------------------------------------------------------------------------- | book_id | author | genre | price | publication_date | number_of_orders | --------------------------------------------------------------------------
换句话说,返回Books表中所有行的每一列,以及一个名为“number_of_orders”的计算列,该列计算每本书出现在Orders表中的次数。 (如果在订单表中没有出现书籍,该书应该列在结果集中,但“number_of_orders”应该为零 。
到目前为止,我已经想出了这个:
SELECT books.book_id, books.author, books.genre, books.price, books.publication_date, count(*) as number_of_orders from books left join orders on (books.book_id = orders.book_id) group by books.book_id, books.author, books.genre, books.price, books.publication_date
这几乎是正确的,但并不完全,因为即使从未在Orders表中列出书籍,“number_of_orders”也将为1。 而且,由于缺乏SQL知识,我相信这个查询是非常低效的。
什么是写这个查询的正确方法? (对于它的价值,这需要在MySQL上工作,所以我不能使用任何其他供应商特定的function)。
提前致谢!
你的查询几乎是正确的,这是做到这一点(和最有效的)
SELECT books.*, count(orders.book_id) as number_of_orders from books left join orders on (books.book_id = orders.book_id) group by books.book_id
COUNT(*)
可以在计数中包含NULL值,因为它计算所有行,而COUNT(orders.book_id)
不会因为它忽略给定字段中的NULL值。
将count(*)
更改为count(orders.book_id)
SELECT b.book_id, b.author, b.genre, b.price, b.publication_date, coalesce(oc.Count, 0) as number_of_orders from books b left join ( select book_id, count(*) as Count from Order group by book_id ) oc on (b.book_id = oc.book_id)
你在计算错误的东西。 你想要计算非空book_id的。
SELECT books.book_id, books.author, books.genre, books.price, books.publication_date, count(orders.book_id) as number_of_orders from books left join orders on (books.book_id = orders.book_id) group by books.book_id, books.author, books.genre, books.price, books.publication_date