2017-04-18 82 views
0

我有當前的SQL語句加入與功能。「在」尋找兩個值

+1

請給我一些樣本數據,給你完美的解決方案。 – Faisal

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

+0

所以你只想要顯示提供海鮮和飲料的供應商? – xQbert

回答

0

您可以使用所有運營商來完成UR要求

SELECT count(distinct s.SupplierID) 
from Products p join Categories c on p.CategoryID = c.CategoryID 
join Suppliers s on s.SupplierID = p.SupplierID and c.CategoryName 
=All (select 'Beverages' as column 
Union all select 'Seafood'); 

你可以給分別有兩個條件,

SELECT count(distinct s.SupplierID) 
    from Products p join Categories c on p.CategoryID = c.CategoryID 
    join Suppliers s on s.SupplierID = p.SupplierID 
Where c.CategoryName ='Beverages' and c.CategoryName= 'Seafood' 
+0

有些奇怪的原因不起作用。有另一種方法嗎? – fredjimbob

+0

現在我已經改變它現在嘗試 – Rams

+0

耶也沒有。這些是我以前試過的方法 – fredjimbob

0

你試過把狀態WHERE子句中,而不是作爲其一部分連接條件?例如:

SELECT count(distinct s.SupplierID) 
from Products p 
join Categories c on p.CategoryID = c.CategoryID 
join Suppliers s on s.SupplierID = p.SupplierID 
WHERE c.CategoryName IN ('Beverages', 'Seafood'); 
+1

Yah只是有和以前一樣的輸出 – fredjimbob

0

如果我假設你想要的是綁兩個類別的供應商名單...

SELECT S.SupplierID 
FROM Products p 
INNER JOIN join Categories c 
    on p.CategoryID = c.CategoryID 
INNER JOIN Suppliers s 
    on s.SupplierID = p.SupplierID 
WHERE c.CategoryName IN ('Beverages', 'Seafood') 
GROUP BY SupplierID 
HAVING count(Distinct c.categoryID) = 2 

的問題是每個類別是在不同的行。所以我們需要找到那些有兩排飲料或海鮮的飲料。因此,我們將類別ID計算在內,並確保兩者都存在,因爲where子句將結果限制爲具有飲料或海鮮類別的供應商。

另一種方法是爲每個類別建立一個連接,但是對於更多的類別名稱會變得繁瑣。

0

如果你想那些提供兩類所有供應商,你可以這樣做:

SELECT count(distinct s.SupplierID) 
from Products p join Categories c on p.CategoryID = c.CategoryID 
     join Suppliers s on s.SupplierID = p.SupplierID 
      and c.CategoryName like 'Beverages' 
where exists (select * from Products where SupplierID = s.SupplierID and 
     CategoryID = (select CategoryID from Category where name like 'Seafood'))