有很多方法可以解決這個問題;最直接的可能是使用一對夫婦的exists
條款,或加入attributes
表兩次,但你也可以使用group by
和having
子句來完成相同的結果:
-- 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.
來源
2015-10-06 00:49:37
jpw
我剛纔已經回答了完全相同的問題在其他SO話題:http://stackoverflow.com/questions/32945964/php-search-mysql-database-using-multiple-select-dropdown-lists – Shadow
我希望重複的東西更好地工作 – Strawberry
你可以在這裏找到類似的東西:http://stackoverflow.com/questions/32948681/mysql-filter-on-many-to-many/32949847 –