我想找到减号查询的两边每个所有者的表名之间的差异。
说我从一个表中有2条select语句,我想这样比较它们:
Select1:
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha';
Select2:
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie';
说alpha的表有表名:a,b,c,而charlie的表有表名b,c。
如果我愿意
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie';
这给了我预期的结果:a。
相反,如果我做相反的事情:
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha';
这给了我预期的结果:空行。
现在,如果我想要表名“ a”和空行,我都将执行:
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie'
Union
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha';
那我什么也没得到。
如何返回“ a”行和空行的总和? 我正在使用Oracle DB
答案 0 :(得分:2)
仅在合并后使用括号
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie'
Union
(
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie') minus
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha'
)
示例
with t1 as
(
select 62054 as sample_id,'2018-09-25 10:18:15' as timestamp,2652 as p_id from dual
union all
select 62054 as sample_id,'2018-09-27 16:44:57' as timestamp,966 as p_id from dual
union all
select 62046 as sample_id,null ,1809 as p_id from dual
union all
select 62046 , '018-09-25 10:18:15' ,2097 from dual
) select * from t1 where p_id=2652
minus
select * from t1 where p_id=966
union
select * from t1 where p_id=2652
minus
select * from t1 where p_id=2652
以上将返回null 但是
with t1 as
(
select 62054 as sample_id,'2018-09-25 10:18:15' as timestamp,2652 as p_id from dual
union all
select 62054 as sample_id,'2018-09-27 16:44:57' as timestamp,966 as p_id from dual
union all
select 62046 as sample_id,null ,1809 as p_id from dual
union all
select 62046 , '018-09-25 10:18:15' ,2097 from dual
) select * from t1 where p_id=2652
minus
select * from t1 where p_id=966
union
(
select * from t1 where p_id=2652
minus
select * from t1 where p_id=2652
)
上面将返回下面
SAMPLE_ID TIMESTAMP P_ID
62054 2018-09-25 10:18:15 2652
答案 1 :(得分:1)
如果您明白我的意思,似乎您想要的是UNION
MINUS
INTERSECT
。计算并集,计算相交,然后在这两个结果集之间进行MINUS
(使用适当的括号,这是您当前的工作失败的原因,因为UNION
和MINUS
具有相同的优先级)
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha' UNION
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie')
MINUS
(SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'charlie' INTERSECT
SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = 'alpha');
我相信,这正确反映了您逻辑的要求。 Zaynul Abadin Tuhin's answer解决了当前的问题。但是我相信您的努力(及其解决方案)掩盖了这里的意图。