2015-10-06 59 views
-1

我想在我的數據庫運行查詢,以顯示產品,有選擇的屬性mysql的連接表查詢的2個值

表1 Products

ID | Product Name 
---|----------------- 
1 Red Car 
2 Blue Car 
3 Yellow Car 

表2 Attributes

Product ID | Attribute ID 
-----------|----------------- 
1   3 
2   3 
3   3 
1   4 
2   4 

例如,我只想顯示具有屬性3和4的產品設置它應該只顯示紅色和藍色的車。但不是黃色的車,因爲沒有爲產品ID設置屬性3

+0

我剛纔已經回答了完全相同的問題在其他SO話題:http://stackoverflow.com/questions/32945964/php-search-mysql-database-using-multiple-select-dropdown-lists – Shadow

+0

我希望重複的東西更好地工作 – Strawberry

+1

你可以在這裏找到類似的東西:http://stackoverflow.com/questions/32948681/mysql-filter-on-many-to-many/32949847 –

回答

1

有很多方法可以解決這個問題;最直接的可能是使用一對夫婦的exists條款,或加入attributes表兩次,但你也可以使用group byhaving子句來完成相同的結果:

-- option 1: using multiple exists clauses 
select p.id, p.productname 
from Products p 
where exists (select 1 from Attributes a where p.ID = a.ProductID and a.AttributeID = 3) 
    and exists (select 1 from Attributes a where p.ID = a.ProductID and a.AttributeID = 4); 

-- option 2: using multiple joins 
select p.id, p.productname 
from Products p 
join Attributes a3 on p.ID = a3.ProductID 
join Attributes a4 on p.ID = a4.ProductID 
where a3.AttributeID = 3 
    and a4.AttributeID = 4; 

-- option 3: using aggregate and having 
select p.id, p.productname 
from Products p 
join Attributes a on p.ID = a.ProductID 
group by p.id, p.productname 
having sum(case when a.AttributeID = 3 then 1 else 0 end) > 0 
    and sum(case when a.AttributeID = 4 then 1 else 0 end) > 0; 

-- option 4: using having and count 
select p.id, p.productname 
from Products p 
join Attributes a on p.ID = a.ProductID 
where a.AttributeID in (3,4) 
group by p.id, p.productname 
having count(distinct a.attributeid) = 2; 

哪種方法是最好的你可能會依賴於你需要的結果和索引等等。

Sample SQL Fiddle.