(PHP/MySQL) Let me preface by saying that this works, and that I’m wondering if there’s a cleaner way. This seems a bit… brutish? And I’m not known for my efficient coding. :-/
TABLE (many-to-many)
scenid mapid
AA 01
AA 02
AA 04
BB 01
BB 04
CC 02
CC 03
CC 05
DD 01
DD 02
DD 03
You are searching for scenarios that have ALL of these maps: 01, 02, 03
(having all + some others is ok)
My current method is to use this query:
SELECT scenid, COUNT(scenid) FROM `TABLE`
WHERE mapid IN ( 01, 02, 03 )
GROUP BY scenid ORDER BY COUNT(scenid) DESC, scenid ASC
Which would produce this list:
scenid COUNT
DD 3
AA 2
CC 2
BB 1
Then, within PHP, I run a while loop that copies scenids to a new array so long as the COUNT is still == the total number of mapids (in this case, 3). This trims off all results that contain only some of the required maps.
Again, this works. But I’m still very new to MySQL & PHP (and they’re my first steps into programming) so I’m always wondering if my “works” is another person’s “did you see that idiot just reinvent the wheel? lulz“
Is there a better way? Thank you for your time.
Your query looks ok, but you could do the filtering in
SQLusingHAVINGclause: