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

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

我有一个表,下面的列

  1. TableX
  2. TB1_ID
  3. TB_GO_ID
  4. TB_RET_ID
  5. TB1_ID TB_GO_ID TB_RET_ID
  6. 1 22 NULL
  7. 2 23 24
  8. 3 25 null

另一张tableTABLEY

  1. TB2
  2. TB_ID
  3. TB2_ID TB_ID
  4. 1 22
  5. 2 22
  6. 3 23
  7. 4 24

我的尝试

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

预期产量

  1. TB1_ID Isexist
  2. 1 yes
  3. 2 yes
  4. 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表达式中的相关子查询:

  1. SELECT tb1_id,
  2. CASE
  3. WHEN EXISTS( SELECT 1
  4. FROM TableY y
  5. WHERE y.tb_id = x.tb_go_id
  6. OR y.tb_id = x.tb_ret_id )
  7. THEN 'yes'
  8. ELSE 'false'
  9. END AS is_exist
  10. FROM TableX x

其中,对于样本数据:

  1. CREATE TABLE TableX (TB1_ID, TB_GO_ID, TB_RET_ID) AS
  2. SELECT 1, 22, NULL FROM DUAL UNION ALL
  3. SELECT 2, 23, 24 FROM DUAL UNION ALL
  4. SELECT 3, 25, NULL FROM DUAL;
  5. CREATE TABLE TableY (TB2_ID, TB_ID) AS
  6. SELECT 1, 22 FROM DUAL UNION ALL
  7. SELECT 2, 23 FROM DUAL UNION ALL
  8. SELECT 3, 23 FROM DUAL UNION ALL
  9. SELECT 4, 24 FROM DUAL;

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

展开查看全部
57hvy0tb

57hvy0tb2#

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

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

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

  1. 13 --
  2. 14 temp as
  3. 15 (select tb1_id, tb_go_id tb_goret_id from tablex where tb_go_id is not null
  4. 16 union
  5. 17 select tb1_id, tb_ret_id from tablex where tb_ret_id is not null
  6. 18 )

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

  1. 19 select distinct t.tb1_id,
  2. 20 case when y.tb_id is not null then 'yes' else 'no' end isexist
  3. 21 from temp t left join tabley y on y.tb_id = t.tb_goret_id
  4. 22 order by t.tb1_id;
  5. TB1_ID ISEXIST
  6. ---------- ----------
  7. 1 yes
  8. 2 yes
  9. 3 no --> NO, because 25 does not exist in TABLEY
  10. SQL>
展开查看全部
apeeds0o

apeeds0o3#

样本数据:

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

输出如下:

相关问题