如何获取尺寸小且颜色为绿色的产品ID列表?
我有一张桌子
prodid | heading | description
20 | color | green
20 | size | s
21 | size | s
22 | size | s
我的查询:
select prodid from tablename
where heading in('color','size') and description in ('green','s');
但是必需的输出是"包含大小和绿色的prodid列表"。
prodid | heading | description
20 | color | green
20 | size | s
任何人都可以帮我写一个查询来获得上面的输出。
答案 0 :(得分:2)
因为您需要产品的颜色和大小行来强加所有条件,所以将表连接到自身:
select t1.prodid
from mytable t1
join mytable t2 on t2.prodid = t1.prodid
where t1.heading = 'color' and t1.description = 'green'
and t2.heading = 'size' and t2.description = '5'
答案 1 :(得分:0)
您可以使用嵌套的'和'来构建查询。和'或' s:
select prodid from tablename where (heading = 'color' and description = 'green') or (heading = 'size' and description = 's');
答案 2 :(得分:0)
select prodid from tablename
where heading = 'color'
and description = 'green'
and prodid in (select prodid from tablename
where heading = 'size'
and description = 's');
答案 3 :(得分:0)
我用这个:
SELECT prodid
FROM mytable a
WHERE EXISTS (
SELECT prodid
FROM mytable b
WHERE b.prodid=a.prodid AND b.heading='size' AND b.description='small'
) AND EXISTS (
SELECT prodid
FROM mytable c
WHERE c.prodid=a.prodid AND c.heading='color' AND c.description='green'
)
即使它使用了3次表,我发现它更具可读性和可扩展性。
如果性能是一个问题,可以通过两次使用该表来完成,如波希米亚建议的那样。但首先要确保你有一个索引(prodid,heading,description)。