oracle 检查另一个表中是否存在值的查询

eulz3vhy  于 2023-04-29  发布在  Oracle
关注(0)|答案(3)|浏览(390)

我有一个表,下面的列

TableX

TB1_ID
TB_GO_ID
TB_RET_ID

TB1_ID  TB_GO_ID    TB_RET_ID
1   22  NULL
2   23  24
3   25  null

另一张tableTABLEY

TB2
TB_ID

TB2_ID  TB_ID
1   22
2   22
3   23
4   24

我的尝试

SELECT  
TB1_ID,
isexist
FROM TABLEX r,TABLEY Y where  Y.TB_ID in (R.TB_GO_ID, R.TB_RET_ID)

预期产量

TB1_ID  Isexist 
1   yes 
2   yes 
3   FALSE

此处isexist取决于此ID TB_GO_ID/TB_RET_ID是否存在于TABLEX中,将此值设置为1,否则将其设置为0。
我写了如下的查询,从tablex和一个变量字段中获取id,该变量字段确定第二个表中是否存在TB_GO_ID、TB_ret_ID。我期待着一个单一的行与表x的细节和一个新的领域,说如果身份证存在于第二个表。

drkbr07n

drkbr07n1#

您可以使用EXISTSCASE表达式中的相关子查询:

SELECT tb1_id,
       CASE
       WHEN EXISTS( SELECT 1
                    FROM   TableY y
                    WHERE  y.tb_id = x.tb_go_id
                    OR     y.tb_id = x.tb_ret_id )
       THEN 'yes'
       ELSE 'false'
       END AS is_exist
FROM   TableX x

其中,对于样本数据:

CREATE TABLE TableX (TB1_ID, TB_GO_ID, TB_RET_ID) AS
SELECT 1, 22, NULL FROM DUAL UNION ALL
SELECT 2, 23, 24 FROM DUAL UNION ALL
SELECT 3, 25, NULL FROM DUAL;

CREATE TABLE TableY (TB2_ID, TB_ID) AS
SELECT 1, 22 FROM DUAL UNION ALL
SELECT 2, 23 FROM DUAL UNION ALL
SELECT 3, 23 FROM DUAL UNION ALL
SELECT 4, 24 FROM DUAL;

输出:
| TB1_ID|存在|
| --------------|--------------|
| 1|是的|
| 二|是的|
| 三|假的|
fiddle

57hvy0tb

57hvy0tb2#

我不知道1、2、3在期望输出中代表什么;我认为这些应该是TB_GO_ID和TB_RET_ID中的值。
假设我是对的,那么:
样本数据:

SQL> with
  2  tablex (tb1_id, tb_go_id, tb_ret_id) as
  3    (select 1, 22, null from dual union all
  4     select 2, 23, 24   from dual union all
  5     select 3, 25, null from dual
  6    ),
  7  tabley (tb2, tb_id) as
  8    (select 1, 22 from dual union all
  9     select 2, 22 from dual union all
 10     select 3, 23 from dual union all
 11     select 4, 24 from dual
 12    ),

查询从这里开始:temp CTE创建存储在TB_GO_IDTB_RET_ID中的唯一非空ID值列表:

13  --
 14  temp as
 15    (select tb1_id, tb_go_id tb_goret_id from tablex where tb_go_id  is not null
 16     union
 17     select tb1_id, tb_ret_id            from tablex  where tb_ret_id is not null
 18    )

最后,检查tabley中是否存在tempID s:

19  select distinct t.tb1_id,
 20    case when y.tb_id is not null then 'yes' else 'no' end isexist
 21  from temp t left join tabley y on y.tb_id = t.tb_goret_id
 22  order by t.tb1_id;

    TB1_ID ISEXIST
---------- ----------
         1 yes
         2 yes
         3 no          --> NO, because 25 does not exist in TABLEY

SQL>
apeeds0o

apeeds0o3#

样本数据:

select *,
case when TB_GO_ID in (select tb_id from TableY) then 'Yes' 
when TB_RET_ID in (select tb_id from TableY) then 'Yes' else 'No' End as IF_Exists  
from tablex

输出如下:

相关问题