mysql 如何计算表中每个外键ID的示例数?

col17t5w  于 2022-12-28  发布在  Mysql
关注(0)|答案(5)|浏览(139)

下面是我的简单SQL问题...
我有两张table:
书籍

-------------------------------------------------------
| book_id | author | genre | price | publication_date |
-------------------------------------------------------

订单

------------------------------------
| order_id | customer_id | book_id |
------------------------------------

我想创建一个查询,返回:

--------------------------------------------------------------------------
| book_id | author | genre | price | publication_date | number_of_orders |
--------------------------------------------------------------------------

换句话说,返回Books表中ALL行的每一列,沿着一个名为'number_of_orders'的计算列,该计算列计算每本书在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上工作,所以我不能使用任何其他特定于供应商的特性)。

t98cgbkg

t98cgbkg1#

您的查询几乎是正确的,这是正确的方法(也是最有效的方法)

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值,因为它忽略给定字段中的NULL值。

dbf7pr2w

dbf7pr2w2#

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)
hi3rlvi2

hi3rlvi23#

count(*)更改为count(orders.book_id)

cnwbcb6i

cnwbcb6i4#

你数错了,你想数非空的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
kkih6yb8

kkih6yb85#

select author.aname,count(book.author_id) as "number_of_books"
from author 
left join book 
on(author.author_id=book.author_id)
GROUP BY author.aname;

相关问题