【问题标题】:Selection of data from one table and if it doesn't exist select from another in Oracle从一个表中选择数据,如果它不存在,则从 Oracle 中的另一个表中选择
【发布时间】:2021-12-14 09:31:42
【问题描述】:

我有 2 个表 - tbl1 和 tbl2

tbl1 has 2 columns -

user_id , updated_on

tbl2 has 2 columns -

account_name , inserted_on

我需要打勾,首先在tbl2中搜索inserted_on日期,如果没有找到,需要从tbl1获取updated_on日期并在日期上加上180天。

流程: tbl2 -> 搜索插入日期 -> 在 tbl2 中找不到 -> 从 tbl1 中获取 updated_on 日期并将 180 天添加到 updated_on 日期

我试过这个:

SELECT UPDATED_ON  FROM tbl1 t1
  WHERE NOT EXISTS(
    SELECT  INSERTED_ON FROM tbl2 t2 WHERE t1.user_id = t2.f_account_name
) ; 

但是当 tbl2 中没有匹配的数据时,这会给出从 t1 开始的 updated_on 日期。

但我也需要inserted_on 日期,例如检查tbl2 选择inserted_on 日期(如果存在),否则检查tbl1 选择updated_on 日期并添加180 天..

【问题讨论】:

    标签: sql oracle join


    【解决方案1】:

    在我看来像外部连接:

    select a.user_id, 
           nvl(b.inserted_on, a.updated_on + 180) as resulting_date
    from tbl1 a left join tbl2 bon a.user_id = b.account_name
    

    【讨论】:

    • 如果在 tbl2 中找不到插入日期,则仅在 updated_on 日期添加 180。 tbl2 -> 搜索插入日期 -> 在 tbl2 中找不到 -> 从 tbl1 中获取 updated_on 日期并将 180 天添加到 updated_on 日期
    • 啊哈;我认为必须将 180 添加到您找到的 any 日期。只是一个反对意见:如果“180”代表“6个月”,请考虑使用ADD_MONTHS,即nvl(b.inserted_on, add_months(a.updated_on, 6)) as resulting_date
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多