使用UNION子句进行SELECT

时间:2014-05-05 05:41:16

标签: sql oracle

例如。我有这两张桌子

//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

但我的问题是选择在波士顿'或者'达拉斯'但不是两者都有,我的输出应该是这样的

DNAME
--------
SCIENCE

为了获得正确的输出,我应该改变什么

4 个答案:

答案 0 :(得分: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 减去

答案 1 :(得分:1)

您可以先筛选出dnames,然后使用group by仅选择一个城市中存在的dnames。

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

答案 2 :(得分:0)

问题是:UNION会自动删除所有重复项。因为DNAME是唯一返回的列,它将删除重复的

修改 对于'DALLAS'或'BOSTON'中DNAME的不同选择,可以这样:

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

答案 3 :(得分:-1)

您可以使用ROWNUM伪列,请参阅小提琴here