admin

使用UNION子句进行选择

sql

例如 。我有这两个表

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

我应该改变什么才能获得正确的输出


阅读 250

收藏
2021-06-07

共1个答案

admin

您应该使用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 减去 它们

2021-06-07