mysql连接表查询2个值

时间:2015-10-06 00:24:59

标签: mysql join

我试图在我的数据库上运行查询以显示具有所选属性的产品

表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设置属性

1 个答案:

答案 0 :(得分: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.