2011-02-13 130 views
8

我在查詢中顯示與其關聯的產品數量的商店列表時遇到問題。我已經玩了很長一段時間了,但是無濟於事。該表具有下述結構:Count()和左連接問題

商店表含有列:idname

產品含有表列:idnamestatusshop

查詢是如下:

select s.name 
     , p.name 
     , count(p.id) 
from Product as p 
     left join Shop as s on p.shop=s.id 
where p.status <> '8796107276379' 
group by 
     s.id 

我沒有得到有0產品的商店。我該如何做到這一點?

底層數據庫是MySQL。

謝謝! Krt_Malta

+0

嘗試頂替右連接,而不是一直 – 2011-02-13 10:03:35

+1

不,這是行不通的。我得到以下錯誤:在[p:product,s right:Shop]中找不到(可見)別名s的類型。 (這是專有的查詢語言) – 2011-02-13 10:10:23

回答

21

您需要在左側購買SHOP,因爲右側可能沒有數據,在這種情況下爲PRODUCT。

不僅如此,您需要將WHERE條件作爲LEFT-JOIN ON條件,以便它在狀態條件下加入產品,並且即使在不需要狀態時也會打折(同時保留店鋪)產品。

select s.name 
     , p.name 
     , count(p.id) 
from Shop as s 
     left join Product as p on p.shop=s.id AND p.status <> '8796107276379' 
group by 
     s.id, p.name 
0

您需要將OR p.status IS NULL添加到where子句中。

select s.name, p.name, count(p.id) 
from Shop s 
left join Product p on p.shop = s.id 
where (p.status <> '8796107276379' OR p.status IS NULL) 
group by s.name, p.name 
+0

Nope沒有工作。爲什麼你認爲應該使用p.status IS NULL? – 2011-02-13 10:16:33

+0

你說你的查詢沒有返回沒有任何產品的商店。如果沒有「OR p.status IS NULL」,你的where子句確實會排除所有這些情況,因爲比較「NULL <>'8796107276379'」永遠不會是真的。 NULL與任何東西都不相等(甚至是另一個NULL),也不等於任何東西。 – Tommi 2011-02-13 10:20:27

1
select s.name 
     , p.name 
     , count(p.id) 
from Shop as s 
     left join Product as p on s.id=p.shop 
where p.status <> '8796107276379' 
group by 
     s.id 
0

我遭受這樣的疑難雜症太多,雖然我不完全知道爲什麼,把謂語的jojn本身,而不是實際的主查詢是如何解決這個問題。

在閱讀本文之前,我實際記錄了整件事情。我用二兩小桌子一個簡單的例子,它說明了我希望的區別,也許這將有助於

http://simpleritsolutions.com/sql/left/join/problems