如何使用联接表中的值过滤一个表中的行

时间:2019-06-10 14:40:49

标签: sql postgresql

products
| id |
------
|  1 |
|  2 |

attributes
| product_id |           value |
--------------------------------
|          1 | Needed value #1 |
|          1 | Needed value #2 |
|          2 | Needed value #1 |

我需要选择同时具有Needed value #1Needed value #2的产品。使用join和where子句无法获取它。它选择每个产品或根本不选择任何产品。有没有比使用多个内部联接更优雅的方法?

SELECT * FROM products
INNER JOIN attributes ON products.id = attributes.product_id
WHERE attributes.value IN ('Needed value #1', 'Needed value #2')
SELECT * FROM products
INNER JOIN attributes ON products.id = attributes.product_id
WHERE attributes.value = 'Needed value #1'
OR /* AND */ attributes.value = 'Needed value #2'

2 个答案:

答案 0 :(得分:1)

您的猫可以执行以下操作:

SELECT * FROM products
INNER JOIN attributes AS a1 ON
    products.id = a1.product_id AND a1.value = 'Needed value #1'
INNER JOIN attributes AS a2 ON
    products.id = a2.product_id AND a2.value = 'Needed value #2'

答案 1 :(得分:0)

您可以通过按product_id对属性表进行分组来完成此操作:

SELECT * FROM products
WHERE id IN (
  SELECT product_id FROM attributes
  WHERE value IN ('Needed value #1', 'Needed value #2')
  GROUP BY product_id
  HAVING COUNT(DISTINCT value) = 2
)

HAVING子句中的条件COUNT(DISTINCT value) = 2确保该产品的两个属性均存在。