MySQL:具有多个匹配项的JOIN和WHERE

MySQL:具有多个匹配项的JOIN和WHERE,mysql,sql,join,Mysql,Sql,Join,我想使用以下查询从products表中选择id为2和5的属性的产品: SELECT `products`.`title`, `products`.`price` FROM `products` LEFT JOIN `products_attributes_mapping` ON `products`.`id` = `products_attributes_mapping`.`product_id` WHERE `products_attributes_mapping`.

我想使用以下查询从
products
表中选择id为2和5的属性的产品:

SELECT `products`.`title`, `products`.`price` 
FROM `products` 
LEFT JOIN `products_attributes_mapping` 
    ON `products`.`id` = `products_attributes_mapping`.`product_id` 
WHERE 
    `products_attributes_mapping`.`attribute_value_id` IN (2) 
    AND `products_attributes_mapping`.`attribute_value_id` IN (5) 
GROUP BY `products`.`id`
我希望返回产品
“示例产品1,蓝色,尺寸1”
。但是我没有得到任何结果,即使id为1的产品在
products\u attributes\u mapping
表中分配了
attribute\u value\u id
2和5

我在中使用了
,因为我希望能够提供多个属性,我仅为示例简化了它

SQL fiddle:

模式

CREATE TABLE `products` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `title` varchar(255) CHARACTER SET utf8 NOT NULL,
    `price` double NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

CREATE TABLE `products_attributes` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;

CREATE TABLE `products_attributes_mapping` (
    `product_id` int(11) NOT NULL,
    `attribute_value_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `products_attributes_values` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `attribute_id` int(11) NOT NULL,
    `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
资料


使用聚合确实是一个解决方案。您可以使用
HAVING
子句来确保产品具有某些属性值:

SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id 
GROUP BY p.id, p.title, p.price
HAVING 
    MAX(pm.attribute_value_id = 2) = 1
    AND MAX(pm.attribute_value_id = 5) = 1
中,此查询返回:

title                            | price
---------------------------------|-------
Example product 1, blue, size 1  | 10
通过添加更多
和MAX(…)=1
条件,可以轻松扩展表达式


另一种选择是使用一系列
WHERE EXISTS
条件和相关子查询来搜索属性表。这同样好,但如果需要添加许多条件,它将扩展为一个较长的查询

一。。您不需要(5)
中的
语句:
和产品属性映射.attribute\u值\u id,因为您正在
中使用
。。在原始的
WHERE
上,只需使用:
attribute\u value\u id IN(2,5)
您的
WHERE
让您尝试选择一个
attribute\u value\u id
同时为2和5的记录。如何将
产品属性映射.attributes\u value\u id IN(2)和产品属性映射.attributes\u value\u id IN(5)
是否返回任何结果<代码>属性\u值\u id
不能同时为2和5。@ItsPete@Eric这就是我想要的。我想获得同时具有in
products\u attributes\u mapping
assigned
attribute\u value\u id
2和5的产品。还有相应的条目:
INSERT-INTO-products\u-attributes\u映射值(1,2)(1,5)
@Hativ当前查询的问题是,要使此查询产生任何结果,
products\u attributes\u mapping
中的单个记录必须同时为2和5。由于一次只能返回一个值,因此不会返回任何结果。GMB下面的解决方案将允许您指定产品需要多个属性。
title                            | price
---------------------------------|-------
Example product 1, blue, size 1  | 10