【问题标题】:Search another table if the first query returns 0如果第一个查询返回 0,则搜索另一个表
【发布时间】:2021-05-13 21:41:26
【问题描述】:

我有这个问题:

select id,name,surname
from db.table
where id_date = 20201101

但是我想如果这个查询返回 0 个结果来运行这个:

select d.id, d.name, d.surname
from db.table2 as d
inner join db.table3 as g
on d.id = g.id
where d.id_date =20201101

这可能吗?我的第一个想法是用子查询来做,但我不知道如何处理结果集

【问题讨论】:

  • 联合所有,不存在。

标签: sql impala


【解决方案1】:

根据 jarlh 的评论:

--"first query"
select id,name,surname
from db.table
where id_date = 20201101

UNION ALL

--"second query"
select d.id, d.name, d.surname
from db.table2 as d
inner join db.table3 as g
on d.id = g.id
where d.id_date =20201101 AND NOT EXISTS(

  select id,name,surname
  from db.table
  where id_date = 20201101

)

如果第一个查询返回结果,则 NOT EXISTS 将为 false,因此第二个查询的整个 where 子句为 false,因此第二个查询没有输出。总体结果是“一些第一个查询结果并没有什么”

相反,如果第一个查询不输出任何内容,则NOT EXISTS (nothing) 为真,第二个查询的输出取决于d.id_date=20201101 的真值。整体查询结果是“没有任何联合所有第二个查询结果”

值得指出的是,这正是“运行这个,如果没有输出运行那个”——它是一个“运行所有这些”,通过考虑布尔值的两边来实现修改后的输出。因此,可能数据库只会运行第一个查询一次,计算出它在两个地方的使用情况,并重用它在两个地方获得的结果,但不能保证 - 它可能是第一个查询运行两次,所以确保它被最佳索引等

【讨论】:

    【解决方案2】:

    正如@jarlh 所说,试试这个

    select id,name,surname
    from db.table
    where id_date = 20201101
    
    union all
    
    select d.id, d.name, d.surname
    from db.table2 as d
    inner join db.table3 as g
    on d.id = g.id
    where d.id_date =20201101 and not exists (
            select 1
            from db.table
            where id_date = 20201101)
    

    【讨论】:

    • 非常感谢。你能解释一下不存在的东西并选择 1 吗?我将不胜感激
    • 不存在是检查第一个表中不存在该值。如果是这样,那么它不会从第二个查询中返回任何内容。子查询实际上不需要返回任何实际值。许多人使用 select 1 表示该值无关紧要。 w3schools.com/sql/sql_exists.asp
    • 补充@Bee_Riii 解释的内容,SELECT 1 不是强制性的,您也可以使用SELECT COLUMN_NAME 甚至*。看看这个Exists / not exists: 'select 1' vs 'select field'
    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 2018-12-18
    • 1970-01-01
    • 2011-05-03
    • 2011-03-13
    • 2020-06-24
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多