在此先感谢您的帮助。来自同一个表的多个MySQL查询
我有一张表标记属性。在该表中是产品项目编号(插针)和属性编号。针的每个属性都在单独的行中
Ex。
pin attribute
111 4
111 5
111 10
112 4
112 5
...
我试图找到一个查询,让我说“选择引脚,如果属性= 4,属性= 5”
的属性是颜色,大小等。所以让所有记录是红色(4)和大小小(5)。
在上面的例子中,它会回位销111和112
迈克
在此先感谢您的帮助。来自同一个表的多个MySQL查询
我有一张表标记属性。在该表中是产品项目编号(插针)和属性编号。针的每个属性都在单独的行中
Ex。
pin attribute
111 4
111 5
111 10
112 4
112 5
...
我试图找到一个查询,让我说“选择引脚,如果属性= 4,属性= 5”
的属性是颜色,大小等。所以让所有记录是红色(4)和大小小(5)。
在上面的例子中,它会回位销111和112
迈克
这应该你使用count
与distinct
的工作:
select pin
from attributes
where attribute in (4,5)
group by pin
having count(distinct attribute) = 2
这将返回有任何引脚属性4和5.
谢谢!它完全按照我的意愿工作。 – user2579643
@ user2579643 - np,很高兴我能帮上忙! – sgeddes
这是“set-set-sets”查询的示例。我主张通过聚合和having
条款来做到这一点。对于你的例子,这看起来像:
select pin
from attributes
group by pin
having sum(attribute = 4) > 0 and
sum(attribute = 5) > 0;
我喜欢这种方法的原因是因为它是灵活的。如果你想要的属性4 或 5,查询将是:
having sum(attribute = 4) > 0 or
sum(attribute = 5) > 0;
如果你想4和5,没有别的:
having sum(attribute = 4) > 0 and
sum(attribute = 5) > 0 and
sum(attribute not in (4, 5)) = 0;
select pin,
group_concat(distinct attribute order by attribute) as atts
from attributes
where attribute in (4,5)
group by pin
having (atts = '4,5');
你仍然有这个查询有问题吗? –