mysql选择id,其中列匹配所有值

mysql选择id,其中列匹配所有值,mysql,sql,Mysql,Sql,我有一张桌子: id filter_id 1 5 2 5 3 5 3 17 4 17 5 17 ID不是唯一的 我需要像这样的东西 SELECT id FROM table WHERE filter = 5 AND filter = 17 但它不返回任何内容,因为筛选器列不能同时为5和17 所以我需要得到id=3的结果 我试过了 SELECT id FROM table WHERE filter IN (5, 17) 但我需要和,而不是手术 谢谢您的帮助。您可以使

我有一张桌子:

id  filter_id
1   5
2   5
3   5
3   17
4   17
5   17
ID不是唯一的

我需要像这样的东西

SELECT id FROM table WHERE filter = 5 AND filter = 17
但它不返回任何内容,因为筛选器列不能同时为5和17

所以我需要得到id=3的结果

我试过了

SELECT id FROM table WHERE filter IN (5, 17)
但我需要和,而不是手术

谢谢您的帮助。

您可以使用:

SELECT  id
FROM table
WHERE filter IN (5,17)
GROUP BY id
HAVING COUNT(DISTINCT filter) = 2
您可以使用:

SELECT  id
FROM table
WHERE filter IN (5,17)
GROUP BY id
HAVING COUNT(DISTINCT filter) = 2

另一种使用
sum

SELECT  id
FROM table
GROUP BY id
HAVING SUM(filter = 5)
and SUM(filter = 17)

另一种使用
sum

SELECT  id
FROM table
GROUP BY id
HAVING SUM(filter = 5)
and SUM(filter = 17)

不分组数据,以防表中有太多行:

SELECT distinct id FROM table t1 WHERE filter_id = 5 and exists (select 1 from table t2 where filter_id = 17 and t1.id = t2.id);

不分组数据,以防表中有这么多行:

SELECT distinct id FROM table t1 WHERE filter_id = 5 and exists (select 1 from table t2 where filter_id = 17 and t1.id = t2.id);