MySQL选择所需的帮助

时间:2012-09-26 17:29:56

标签: mysql

+---+---+
| A | B |
+---+---+
| 1 | 1 |
+---+---+
| 1 | 2 |
+---+---+
| 1 | 3 |
+---+---+
| 1 | 4 |
+---+---+
| 2 | 2 |
+---+---+
| 2 | 4 |
+---+---+
| 3 | 2 |
+---+---+
| 4 | 3 |
+---+---+

给定B中的一组值,如何从A中选择所有B值共享的值?例如:

  • 值1,2,3,4应返回1
  • 值2,4应返回1,2
  • 值1,2,3,4,5应返回空集

到目前为止,我有:

SELECT A 
FROM (table_A) 
JOIN table_B ON A = A 
WHERE B = '1' OR B = '2' OR B = '3' OR B = '4'

这显然远离了我的需要。我真的很喜欢这里,不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

select A 
from tableA
JOIN tableB ON tableA.A = tableB.A
where B in (1,2,3,4)
group by A
having count(distinct B) = 4

having子句中的数字必须是in子句中的元素数。

答案 1 :(得分:0)

如果你可以保证A, B是一个独特的群体,并且可以正常工作。

SELECT A 
FROM mytable
WHERE B in (1,2,3,4,5)
GROUP BY A
having count(*)=5;