简体   繁体   中英

Mysql find parent records where given values are found in all child records

I have two tables:

Parent:
+-----------+-----------+
| parent_id | something |
+-----------+-----------+
|       123 | x         |
|       231 | y         |
|       455 | z         |
+-----------+-----------+

Relations:
+-----+----------+--------------+--------------+
| id  | parent_id| option_name  | option_value |
+-----+----------+--------------+--------------+
|  1  |     123  | Colors       | aaa          |
|  2  |     231  | Colors       | bbb          |
|  3  |     456  | Colors       | aaa          |
|  4  |     456  | Country      | ddd          |
+-----+----------+--------------+--------------+

What I want to do, is take all rows from Parent that have all options I want in the Relations table:

Eg:

 SELECT * FROM Parent P
 LEFT JOIN Relations R ON R.parent_id = P.parent_id
 WHERE option_name = Colors 
 AND option_value = aaa 
 AND option_name = Country
 AND option_value = ddd

For the above query I would like the row with parent_id 455 returned, since it has both options.

PS: - The above query is wrong, I gave it just as an example for what I want to do - I will have more than 2 options -> its practically from 1 to unlimited

I think this can be done with left join (for each option needed, add a different left join ... but the options table could reach millions of records someday, and I don't know how optimized will this query be)

You can use HAVING:

SELECT *, count(option_name) AS total FROM Parent P
 LEFT JOIN Relations R ON R.parent_id = P.parent_id
 WHERE (option_name = Colors 
 AND option_value = aaa)
 OR (option_name = Country
 AND option_value = ddd)
 HAVING total > 1

You change the HAVING condition to find the number of options you are looking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM