I have table structure like this:
ID cond 1 5 1 2 1 6 8 2 9 1 9 5
When I want to select rows that contain one or more conditions i use OR (…WHEN cond=2 OR cond=6 GROUP BY ID…)
But how to select rows that contain more than one condition simultaneously grouped by ID? E.g. when i want to find rows that contain cond 2 and 6, it returns only ID 1
Thanks
There are multiple ways of doing this.
Using
COUNT(fastest):Using
EXISTS(using nested loops, slower on very large tables, but less cryptical and more xtensible than theCOUNTvariant):Using
GROUP_CONCAT(a MySql specific variation on the COUNT theme, but if you ever want exact matches, e.g. cond=2 and cond=6 an no other cond, then the below, altered to readSELECT id, GROUP_CONCAT(DISTINCT cond ORDER BY cond) AS conds ... WHERE conds='2,6'will perform best)