2013-08-18 97 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

然而,在實踐中,最好使用分組,如在其它的答案。