2011-09-15 79 views
39

這是我簡單的SQL問題...如何計算表中每個外鍵ID的實例數?

我有兩個表:我想創建一個返回查詢

書籍

------------------------------------------------------- 
| 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表中顯示的次數。 (如果一本書沒有在訂單表會發生,這本書應該結果集中上市,但「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 

這是幾乎權,但並不完全,因爲「number_of_orders」將於1即使一本書從來沒有在訂單表中列出。此外,由於我缺乏SQL的知識,我敢肯定,這查詢效率很低

什麼是寫這個查詢的正確方法? (對於它的價值,這需要在MySQL上工作,所以我不能使用任何其他供應商特定的功能)。

在此先感謝!

回答

62

您的查詢幾乎是正確的,它是做正確的方式(也是最有效的)

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值。

+2

你的最後一條語句可能會有點誤導。 COUNT函數本身在彙總數據時忽略NULL值。 COUNT(*)在這裏返回錯誤計數的原因是因爲其計數行而不是特定列。只是想澄清爲OP –

+0

更新了答案,thx。 – Fabio

+0

@Fabio調用這個特定的查詢是什麼,用於計算其他表中的相關條目?有沒有學術名字? –

5

變化count(*)count(orders.book_id)

1

你算錯了。您想要計算非空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 
4
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) 
相關問題