我正在使用减法运算和case函数,但没有得到答案

问题描述 投票:0回答:3

enter image description here

输入数据:

table1   table2
id        id 
1         2
2         3
3         4
4         8
5         9
7         6       

输出数据:

id 状态
1 不在表2中
5 不在表2中
7 不在表2中
8 不在表1中
9 不在表1中
6 不在表1中

我认为在此表中使用减号运算符和 case 函数,但我没有得到答案。我不知道什么时候用例功能在这里

sql:

select * from table1
minus 
select * from table2 
case when select * from table1
minus 
select * from table2 
then id
else not in table1
end as status
sql oracle
3个回答
0
投票

您可以使用

FULL OUTER JOIN

SELECT COALESCE(t1.id, t2.id) AS id,
       NVL2(t1.id, 'Not in table2', 'Not in table1') AS status
FROM   table1 t1
       FULL OUTER JOIN table2 t2
       ON t1.id = t2.id
WHERE  t1.id IS NULL
OR     t2.id IS NULL

对于样本数据:

CREATE TABLE table1 (id) AS
SELECT LEVEL FROM DUAL WHERE LEVEL != 6 CONNECT BY LEVEL <= 7;

CREATE TABLE table2 (id) AS
SELECT LEVEL FROM DUAL WHERE LEVEL NOT IN (1, 5, 7) CONNECT BY LEVEL <= 9;

输出:

身份证号码 状态
6 表1中没有
8 表1中没有
9 表1中没有
7 表2中没有
5 表2中没有
1 表2中没有

小提琴


0
投票

您想要的是完整的外部联接:

with table1 as (select id from (select level id from dual connect by level <=10) where id IN (1,2,3,4,5,7)),
     table2 as (select id from (select level id from dual connect by level <=10) where id IN (2,3,4,8,9,6))
select nvl(table1.id,table2.id) id,
       case when (table1.id is null) then 'not in table1'
            when (table2.id is null) then 'not in table2'
       end status
  from table1 full outer join table2 on table1.id = table2.id       
 where table1.id is null or table2.id is null

0
投票

您可以使用各种选项;正如您提到的集合运算符,具体方法如下:

样本数据:

SQL> with
  2  table1 (id) as
  3    (select 1 from dual union all
  4     select 2 from dual union all
  5     select 3 from dual union all
  6     select 4 from dual union all
  7     select 5 from dual union all
  8     select 7 from dual
  9    ),
 10  table2 (id) as
 11    (select 2 from dual union all
 12     select 3 from dual union all
 13     select 4 from dual union all
 14     select 8 from dual union all
 15     select 9 from dual union all
 16     select 6 from dual
 17    )

查询从这里开始:

 18  select a.id, 'not in table2' status from table1 a
 19  minus
 20  select b.id, 'not in table2'        from table2 b
 21  union
 22  select b.id, 'not in table1'        from table2 b
 23  minus
 24  select a.id, 'not in table1' status from table1 a;

        ID STATUS
---------- -------------
         7 not in table2
         5 not in table2
         1 not in table2
         6 not in table1
         9 not in table1
         8 not in table1

6 rows selected.

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.