2008-09-24 116 views
2

我有一個多對多的索引表,我想對它做一個包含/排除類型的查詢。多對多表查詢

fid實際上是一個整數索引,但在這裏作爲更容易理解的字母。下面是一個示例表:

表t

eid | fid 
----+---- 
1 | A 
1 | B 
1 | C 
2 | B 
2 | C 
3 | A 
3 | C 
4 | A 
4 | B 
5 | B 

這裏有我想要一些樣本查詢。

  1. 什麼eids fid B,而不是A? (回答eid 2和5)
  2. 什麼eids fid C,而不是A? (回答eid 2)

我似乎無法弄清楚這樣做的查詢。

我已經嘗試了自加入這樣的:

select * 
from t as t1 
join t as t2 
where t1.eid=t2.eid 
    and t1.fid!=t2.fid 
    and t1.fid=B and t2.fid!=A 

這是行不通的,因爲它仍然會返回行,其中EID = 1,FID = C。

我清楚我想要什麼嗎?

回答

3

下面是一個查詢的示例(2個作品大致相同)

select t1.eid 
    from t t1 
where t1.fid = 'B' 
    and not exists 
     (select 1 
      from t t2 
     where t2.eid = t1.eid 
      and t2.fid = 'A') 
+0

謝謝,在mysql中工作 – Pyrolistical 2008-09-24 19:31:12

7

使用set subtraction

Select eid from t where fid = 'B' 
EXCEPT 
select eid from t where fid = 'A' 
+0

偉大的提示;我從來沒有使用EXCEPT語法。 – 2008-09-24 19:25:40

1

您可以使用從T A子選擇

選擇EID其中FID = 'C' 和EID不是(選擇在t EID其中FID = 'A')

0

MySQL 5.0支持存在/不存在的地方,如Nigel和Mike所述。

0

版直聯接可能比使用更快的存在:

 
Select t1.eid 
From #test t1 
     left join (
      Select eid 
      From #test t2 
      Where fid = 'A' 
      Group by eid 
     ) t2 on t2.eid = t1.eid 
Where t1.fid = 'B' 
     and t2.eid is null 
0

它應該能夠做到這一點,而不使用子查詢:

SELECT DISTINCT t1.eid 
FROM table1 AS t1 
    LEFT JOIN table1 AS t2 ON (t1.eid = t2.eid AND t2.fid = 'A') 
WHERE t2.eid IS NULL 
    AND t1.fid = 'B'; 

做你的第二個例子搜索,只需將值「B」更改爲「C」。

0

調查MINUS操作員。它的工作方式與UNION類似,只不過它會減去UNION添加的位置。以前的答案與「EXCEPT」一詞可能是同一事物的不同關鍵字。

下面是一個未經測試的答案:

select eid 
from t 
where fid = 'A' 
minus 
select eid 
from t 
where fid = 'B'