如果第一个查询 returns 0,则搜索另一个 table
Search another table if the first query returns 0
我有这个问题:
select id,name,surname
from db.table
where id_date = 20201101
但我想如果这个查询 returns 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
这可能吗?我的第一个想法是用子查询来做,但我不知道如何处理结果集
如@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)
根据 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
)
如果第一个查询 returns 结果,则 NOT EXISTS 将为假,因此第二个查询的整个 where 子句为假,因此第二个查询没有输出。总体结果是“some first query results union all nothing”
相反,如果第一个查询什么都不输出,则 NOT EXISTS (nothing)
为真,第二个查询的输出取决于 d.id_date=20201101
的真实性,总体查询结果为“nothing union all some second query结果
值得指出的是,这正是“运行 this, if no output 运行 that” - 它是“运行 all this”,通过考虑布尔真值的两边。因此,它 可能 是数据库只会 运行 第一个查询一次,计算出它在两个地方的使用,并在两个地方重用它得到的结果,但是不能保证-第一个查询可能是 运行 两次,因此请确保它已被优化索引等
我有这个问题:
select id,name,surname
from db.table
where id_date = 20201101
但我想如果这个查询 returns 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
这可能吗?我的第一个想法是用子查询来做,但我不知道如何处理结果集
如@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)
根据 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
)
如果第一个查询 returns 结果,则 NOT EXISTS 将为假,因此第二个查询的整个 where 子句为假,因此第二个查询没有输出。总体结果是“some first query results union all nothing”
相反,如果第一个查询什么都不输出,则 NOT EXISTS (nothing)
为真,第二个查询的输出取决于 d.id_date=20201101
的真实性,总体查询结果为“nothing union all some second query结果
值得指出的是,这正是“运行 this, if no output 运行 that” - 它是“运行 all this”,通过考虑布尔真值的两边。因此,它 可能 是数据库只会 运行 第一个查询一次,计算出它在两个地方的使用,并在两个地方重用它得到的结果,但是不能保证-第一个查询可能是 运行 两次,因此请确保它已被优化索引等