双"和" SQL查询

时间:2015-10-25 20:02:27

标签: sql sqlalchemy

我正在处理下表的SQL查询:

product_id | type | value
1 | gender  | female
1   | age   |  1-10
2   | gender    | female
2 | age |  1-10
3   | gender    | male
3 | age  | 11-20
4   | gender     | female
4   | age    | 11-20
5   | gender    | male
5   | age   | 1-10

产品(不同的表,product_id是外键)具有性别或年龄类型的属性。对于性别=女性和年龄= 1-10的情况,我想获得不同的产品ID。

我尝试了以下查询:

SELECT distinct product_id 
FROM Attributes 
WHERE (type = "gender" and value  ="female") 
  and (type = "age" and value = "1-10")

我希望得到产品ID 1和2.但是我什么都没回来。

知道我做错了吗?

2 个答案:

答案 0 :(得分:1)

它不起作用的原因是因为没有同时具有Gender类型和Age类型的行。我会选择子查询。

SELECT DISTINCT product_id FROM Attributes WHERE (type = "age" and value ="1-10") 

AND product_ID IN (

SELECT distinct product_id FROM Attributes WHERE (type = "gender" and value ="female"))

答案 1 :(得分:0)

我不认为样本表中的任何内容都是

(type = "gender" and value ="female") and (type = "age" and value = "1-10")

我认为这个子选择的内连接可能会起作用:

SELECT DISTINCT A.product_id 
FROM Attributes A 
INNER JOIN A.product_id = B.product_id
  (
    SELECT product_id 
    FROM Attributes 
    WHERE (type = "age" and value = "1-10") 
  ) B

WHERE (A.type = "gender" and A.value ="female") 

这应该是一个不同的产品ID列表,其中性别为女性,年龄为“1-10”