我有以下表结构:
id product_id attribute_id attribute_val_id
138 18 29 304
137 17 29 304
78 17 20 161
79 17 21 301
80 17 22 94
我想选择产品ID(例如17),其attribute_val_id等于:304和161和301.
我试过了:
SELECT DISTINCT product_id FROM `products_attribute_rel`
WHERE attribute_val_id = 304
AND attribute_val_id = 161
AND attribute_val_id = 301
但有了这个,我得到空洞的结果。 MYSQL IN
句也没有用。
有什么想法吗?
答案 0 :(得分:3)
SELECT product_id
FROM products_attribute_rel
WHERE attribute_val_id IN (161, 301, 304)
GROUP BY product_id
HAVING COUNT(DISTINCT attribute_val_id) >= 3;
您应该在表上包含(attribute_val_id,product_id)索引,以使查询更快。
答案 1 :(得分:1)
这应该有所帮助:
SELECT DISTINCT p1.product_id
FROM products_attribute_rel p1
INNER JOIN products_attribute_rel p2 on p1.product_id = p2.product_id
INNER JOIN products_attribute_rel p3 on p1.product_id = p3.product_id
WHERE p1.attribute_val_id = 304
AND p2.attribute_val_id = 161
AND p3.attribute_val_id = 301;
答案 2 :(得分:1)
也许这就是你想要做的事情?
SELECT DISTINCT product_id
FROM products_attribute_rel
WHERE attribute_val_id = 304
AND product_id IN (
SELECT product_id
FROM products_attribute_rel
WHERE attribute_val_id = 161
AND product_id IN (
SELECT product_id
FROM products_attribute_rel
WHERE attribute_val_id = 301
)
);
虽然没有测试过。
答案 3 :(得分:0)
1个字段无法拥有多个值,请改用OR
:
SELECT DISTINCT product_id FROM `products_attribute_rel`
WHERE attribute_val_id = 304
OR attribute_val_id = 161
OR attribute_val_id = 301