[英]Select item from many-to-many table that has all these details… proper solution?
(PHP/MySQL) Let me preface by saying that this works, and that I'm wondering if there's a cleaner way. (PHP / MySQL)首先,我要说这可行,并且我想知道是否有更清洁的方法。 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 您正在搜索具有以下所有地图的方案: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). 然后,在PHP中,我运行一个
while
循环,将scenids复制到一个新数组,只要COUNT
仍然==
mapids的总数(本例中为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 "
但是我对MySQL和PHP还是很陌生(它们是我编程的第一步),所以我一直想知道我的“ 作品 ”是否是另一个人的作品, “ 你看到那个白痴只是在重新发明轮子吗? lulz ”
Is there a better way? 有没有更好的办法? Thank you for your time.
感谢您的时间。
Your query looks ok, but you could do the filtering in SQL
using HAVING
clause: 您的查询看起来还可以,但是您可以使用
HAVING
子句在SQL
进行过滤:
SELECT scenid, COUNT(*)
FROM `TABLE`
WHERE mapid IN ( 01, 02, 03 )
GROUP BY scenid
HAVING COUNT(*) = 3
ORDER BY scenid ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.