2014-05-05 110 views
2

例如。有這兩個表我SELECT使用UNION子句

//DEPARTMENT 
DNAME   CITY 
-------------------- 
RESEARCH  BOSTON 
    IT   CITY 
SCIENCE  DALLAS 
RESEARCH  DALLAS 

因此,使用我這個說法

(SELECT DNAME FROM DEPARTMENT WHERE CITY='BOSTON') 
UNION 
(SELECT DNAME FROM DEPARTMENT WHERE CITY='DALLAS'): 

使用此聲明我得到這個輸出

DNAME 
----- 
RESEARCH 
SCIENCE 

但我的問題是選擇無論是在「波士頓或'DALLAS'但在兩者中,我的輸出應該是這樣的

DNAME 
-------- 
SCIENCE 

我應該改變什麼以獲得正確的輸出

回答

3

您應該使用INTERSECTMINUS(對於Oracle):

-- At least at Boston or at Dallas 
(SELECT DNAME 
    FROM DEPARTMENT 
    WHERE CITY = 'DALLAS' 

UNION 

SELECT DNAME 
    FROM DEPARTMENT 
    WHERE CITY = 'BOSTON') 

MINUS 

-- At Boston and at Dallas 
(SELECT DNAME 
    FROM DEPARTMENT 
    WHERE CITY = 'DALLAS' 

INTERSECT 

SELECT DNAME 
    FROM DEPARTMENT 
    WHERE CITY = 'BOSTON') 

由於UNION增加子查詢向上而EXCEPT/MINUS減去他們

0

問題是:UNION會自動刪除所有重複項。因爲,DNAME是唯一返回的列,它會刪除重複

編輯 對於「達拉斯」或「波士頓要麼DNAME的不同選擇,這樣的事情:

SELECT DNAME FROM DEPARTMENT 
       WHERE (CITY='BOSTON' and CITY<>'DALLAS') 
1

可以先篩選出dnames,然後使用GROUP BY只選擇那些只出現在一個城市dnames。

select dname 
    from department 
where city in ('BOSTON', 'DALLAS') 
group by dname 
having count(city) = 1;