选择一个带有两个左连接的条目。 SQL

时间:2015-03-10 09:48:37

标签: sql postgresql

实施例 如果两个产品

id  name
1   product A
2   product B

对于我所属的每种产品

id product_id value
1  1           1
2  1           2
3  2           3
3  2           4

我需要按属性值选择产品。 我需要具有1和2值属性的产品。

此查询不起作用:

SELECT *
FROM product
LEFT JOIN attribute ON product.id = attribute.product_id
WHERE attribute.value = 1 AND attribute.value = 2;

4 个答案:

答案 0 :(得分:3)

SELECT *
FROM product p
LEFT JOIN attribute a ON p.id = a.product_id
WHERE a.value IN ('1','2')

答案 1 :(得分:3)

通过分组来查找具有1和2属性的产品ID。从该组中找到的产品ID中选择产品:

SELECT *
FROM product_table
WHERE id IN (select product_id
             from attribute_table
             where value in (1,2)
             group by product_id
             having count(distinct value) = 2)

替代解决方案,双联接:

SELECT *
FROM product_table
  JOIN attribute_table a1 ON product_table.id = a1.product_id
                          AND a1.value = 1
  JOIN attribute_table a2 ON product_table.id = a2.product_id
                          AND a2.value = 2

答案 2 :(得分:3)

要重新解释您的问题,您确实需要这些产品,其中12 属于其属性值:

SELECT    product.*
     -- , array_agg(attribute.value) attribute_values
     -- uncomment the line above, if needed
FROM      product
LEFT JOIN attribute ON product.id = attribute.product_id
GROUP BY  product.id
HAVING    array_agg(attribute.value) @> ARRAY[1, 2];

答案 3 :(得分:1)

如果您的意思是值1或2

SELECT *
FROM product p
LEFT JOIN attribute a ON p.id = a.product_id
WHERE a.value IN ('1', '2');