我有这个从codeigniter生成的sql语句
SELECT * FROM (`products`) LEFT JOIN `products_attributes` ON `products_attributes`.`product_id` = `products`.`id` WHERE `products`.`category` = '1' AND `products`.`sub_category` = '1' AND `products_attributes`.`attribute_id` = '3' AND `products_attributes`.`attribute_id` = '4' AND `products_attributes`.`attribute_id` = '5' GROUP BY `products`.`id`
我有这些表
产品: products_attributes:
我需要获得仅具有所有属性的产品,因此如果属性为3,4,5,我将获得产品id = 1,如果属性为3,4,5,6我将无法获得产品id = 1
答案 0 :(得分:1)
您的SQL查询完全错误。你做的是: 给我记录的是attribute_id = 3 AND attribute_id = 4 AND attribute_id = 5 AND attribute_id = 6.一行不能同时等于3和4。 您需要的是以多种不同的方式实现的。例如:
SELECT
products.id
FROM products
JOIN products_attributes ON products_attributes.product_id = products.id
WHERE
products.category = '1'
AND `products_attributes`.`attribute_id` IN (3,4,5,6)
GROUP BY
products.id
HAVING COUNT(DISTINCT `products_attributes`.`attribute_id`) = 4
如果你只指定IN ...那么它将占用至少有1个这样的attribute_id
的所有记录答案 1 :(得分:-1)
试试这个:
SELECT * FROM (`products`)
LEFT JOIN `products_attributes`
ON `products_attributes`.`product_id` = `products`.`id`
WHERE `products`.`category` = 1
AND `products`.`sub_category` = 1
AND `products_attributes`.`attribute_id` IN (3, 4, 5)
GROUP BY `products`.`id`