我有一个包含id和值的表。他们只是在一起。
ID VALUE
1 value1
1 value2
2 value1
3 value2
3 value3
3 value4
4 value3
5 value1
假设我被赋予值“value2”和“value3”,我想选择与这些值匹配的ID(即3)
我可以
SELECT ID FROM table WHERE VALUE IN("value2", "value3")
但是,它返回的值也匹配任何一个。有没有办法只查询匹配这两个值的那些?
答案 0 :(得分:1)
你应该使用GROUP BY和HAVING
SELECT ID FROM table WHERE VALUE IN("value2", "value3") GROUP BY ID HAVING COUNT(*) = 2
答案 1 :(得分:1)
尝试以下方法:
SELECT id FROM table WHERE value = "value2" and id in (SELECT id FROM table WHERE value = "value3")
答案 2 :(得分:1)
SELECT t1.id FROM table AS t1 JOIN table AS t2 ON t1.id=t2.id
WHERE t1.value="value2" AND t2.value="value3"