Mysql获取在不同(关系)表上具有多个值的记录(manyToMany)

时间:2017-11-20 09:46:25

标签: mysql sql doctrine

我需要一些帮助来根据加入项目表及其值表的条件获取记录,具有多个搜索值。

项目表

+----+-----------+
| id |   title   |
+----+-----------+
| 82 | Test ITEM |
+----+-----------+

属性表

+----+--------------+
| id |  Attribute   |
+----+--------------+
|  1 | An Attribute |
+----+--------------+

项目属性值表

+----+---------+--------------+-----------+
| id | item_id | attribute_id | option_id |
+----+---------+--------------+-----------+
|  1 |      82 |            1 |        25 |
|  1 |      82 |            1 |         3 |
+----+---------+--------------+-----------+

我做了什么:

SELECT 
p.*
FROM 
product_products p 
LEFT JOIN
product_attribute_values v ON v.product_id = p.id
LEFT JOIN
product_attribute_options o ON o.id = v.option_id
WHERE 
(p.id = 82 OR p.parent_id = 82) AND
(o.id IN (25, 3))
GROUP BY p.id

但此查询存在问题,因为它返回所有具有3 OR 25值的项目。

我想只返回同时包含25和3个值的项目。

试过这个: Advanced Mysql Query to get master record if two conditions matches on different rows of child records

同样的结果。

请帮忙。

1 个答案:

答案 0 :(得分:2)

尝试此查询

option_id

添加SELECT p.*,o.id FROM ( SELECT p.id,p.title FROM product_products p JOIN product_attribute_values v ON v.product_id = p.id JOIN product_attribute_options o ON o.id = v.option_id AND o.id IN (25, 3) WHERE (p.id = 82 OR p.parent_id = 82) GROUP BY p.id,p.title HAVING COUNT(DISTINCT o.id) = 2 ) p JOIN product_attribute_values v ON v.product_id = p.id JOIN product_attribute_options o ON o.id = v.option_id AND o.id IN (25, 3)

StreamReader