2013-08-18 98 views
1

我在数据库中有一个简单的m-to-n表,需要执行AND搜索。该表如下所示:AND查询m-to-n表

column a | column b 
1   x 
1   y 
1   z 
2   x 
2   c 
3   a 
3   b 
3   c 
3   y 
3   z 
4   d 
4   e 
4   f 
5   f 
5   x 
5   y 

我希望能够说“给我列A,其中它在B列的X和Y(返回1和第5这里),但我无法弄清楚如何以形成该查询。

我试图SELECT column_a FROM table WHERE column_b = x AND columb_b = y但似乎如果列在某种程度上都将只返回。这是根本可能的,还是我应该有不同的表格布局?

+0

请指定标记您的DBMS –

回答

1

这里有一种方法:

SELECT a 
FROM Table1 
WHERE b IN ('x', 'y') 
GROUP BY a 
HAVING COUNT(DISTINCT(b)) = 2 

SQL Fiddle

如果你保证(A,B)是独一无二的,你可以摆脱DISTINCT的为好。

1

这是一个“设置内集”子查询的一个例子。我喜欢用group by并把逻辑having子句中:

select column_a 
from table 
group by column_a 
having sum(case when column_b = x then 1 else 0 end) > 0 and 
     sum(case when column_b = y then 1 else 0 end) > 0; 

的每个sum()having子句中计数匹配的条件之一的行的数量。

这原来是相当一般的。所以,你可以通过添加一个条款,检查z

select column_a 
from table 
group by column_a 
having sum(case when column_b = x then 1 else 0 end) > 0 and 
     sum(case when column_b = y then 1 else 0 end) > 0 and 
     sum(case when column_b = z then 1 else 0 end) > 0; 

或者,通过使用or代替and使其 “X” 或 “Y”:

select column_a 
from table 
group by column_a 
having sum(case when column_b = x then 1 else 0 end) > 0 or 
     sum(case when column_b = y then 1 else 0 end) > 0; 
0

是否根本可能?是。看到为什么这将是最简单的方法是看快速和肮脏的解决方案,使用INTERSECT:

select a from your_table where b = 'x' 
intersect 
select a from your_table where b = 'y' 

第一句返回1,2,和5;第二返回1,3和5

然而,在实践中,最好使用分组,如在其它的答案。