我有一个类似于下面的表格设置。
genre_id series_id 1 4 1 2 2 5 4 1 2 4 3 3
What I want to do is to be able to find all series based on the mix of genres selected.
For example finding all series that have a genre id of 1 and 2. Hypothetically the result I want is the series ID of 4.
If I use
SELECT series_id FROM table WHERE genre_id = 1 AND genre_id = 2
它什么都不返回。
如果我用
SELECT series_id FROM table WHERE genre_id in (1, 2)
它返回 1 和 2 中的所有内容。但我只想要 genre_id 相交的行。
有什么办法吗?
最佳答案
这应该可以解决问题:
SELECT series_id FROM table
WHERE genre_id IN (1, 2)
GROUP BY series_id
HAVING COUNT(*) = 2
请注意,这是假设 (genre_id, series_id) 对是唯一的。如果不是,则必须将 HAVING
子句更改为
HAVING COUNT(DISTINCT genre_id) = 2
另请注意,HAVING
子句中的数字 2
必须与 IN
子句中的项目数量相匹配。
关于php - MYSQL:查找多个ID匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341118/