SQL子集查询

时间:2015-07-25 11:09:42

标签: mysql sql subquery

我在创建SQL表的查询时遇到问题。我正在尝试创建的查询显示了"服装"类别中的产品数量。并且不显示附件,例如作为T恤或运动衫输入的产品清单。

以下是已创建的表格:

list = ["simon", "tom", "sarah", "peter", "jane"]
word = input()
if word.lower() in list:
    print('Ok')
    #continue with rest of program
else:
     print('No, sorry')

2 个答案:

答案 0 :(得分:2)

如果我理解正确,这是一个set-within-sets查询。您正在寻找至少有一个“衣服”类别的产品,并且没有一个类别不是衣服。我使用group byhaving来解决此问题,因为它非常灵活:

select pc.product_id
from Product_categories pc join
     categories c
     on pc.category_id = c.category_id
group by pc.product_id
having sum(case when c.structure like 'Clothes%' then 1 else 0 end) > 0 and
       sum(case when c.structure not like 'Clothes%' then 1 else 0 end) = 0;

如果您只想要计数,那么您可以将其用作子查询并使用count(*)

编辑:

小记。这个问题现在用MySQL标记,它有having子句方便的简写:

having sum(c.structure like 'Clothes%') > 0 and
       sum(c.structure not like 'Clothes%') = 0;

答案 1 :(得分:0)

尝试此查询

select * from products a
join Product_categories b on a.product_id=b.product_id
join categories c on b.category_id=b.category_id
where c.name like '%Clothes%'