试试这个:
SELECT DISTINCT
p.product_id,
p.product_name
FROM Product p
INNER JOIN attr_detail ad ON p.product_id = ad.product_Id
INNER JOIN Attribute a ON a.attr_id = ad.attr_id
WHERE a.attr_id IN(1, 2);
这会给你:
| PRODUCT_ID | PRODUCT_NAME |
---------------------------------------
| 1 | amazonite |
| 2 | agate |
| 3 | Product has only white |
请注意:这将为您提供具有white
或oval
形状的产品名称。但是,如果您只寻找同时具有这两种形状的产品,则必须像这样修改您的查询:
SELECT DISTINCT
p.product_id,
p.product_name
FROM Product p
INNER JOIN
(
SELECT product_id
FROM attr_detail
WHERE attr_id IN(1, 2)
GROUP BY product_id
HAVING COUNT(DISTINCT attr_id) = 2
) ad ON p.product_id = ad.product_Id;
这会给你:
| PRODUCT_ID | PRODUCT_NAME |
-----------------------------
| 1 | amazonite |
| 2 | agate |
请阅读有关JOIN
s 的更多信息。在这里您可以找到有关此的有用信息:
对于我在第二个查询中所做的:
SELECT product_id
FROM attr_detail
WHERE attr_id IN(1, 2)
GROUP BY product_id
HAVING COUNT(DISTINCT attr_id) = 2
这称为关系除法。