php - MYSQL:查找多个ID匹配的行

标签 php mysql relational-division

我有一个类似于下面的表格设置。

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/

相关文章:

php - 在没有时区偏移的情况下将 MYSQL 时间戳转换为 ISO-8601

php - 可湿性粉剂 : Blank date/time from php time()

php - 在 php 和 mySQL 中将 DATE 转换为 DATETIME

mysql - 在同一列上使用多个 WHERE 条件进行选择

sql-server - MSSQL 选择 "vertical"-where

php - Yii:STAT 与条件的关系

PHP计算年龄

php - Codeigniter 用户 session 错误

php - MySQL/PHP 基于字段对行进行排序

mysql - 查找具有多个链接行的行