用于查询联合的Postgresql合并模拟
我有一个这样的问题用于查询联合的Postgresql合并模拟,sql,postgresql,union,coalesce,Sql,Postgresql,Union,Coalesce,我有一个这样的问题 select house, street, town, 10 as weight from addresses where house match query, street match query, city match query union all select house, street, town, 5 from addresses where street match query, city match qu
select house, street, town, 10 as weight
from addresses
where
house match query,
street match query,
city match query
union all
select house, street, town, 5
from addresses
where
street match query,
city match query
我希望仅当第一个查询为空时,才执行第二个查询。我知道我可以添加where子句并检查上一个查询的结果,但是如果我添加3或4个可选的子查询,那就太庞大了
我知道这在plpgsql中是可行的,但也许已经有了测试过的标准函数或语法 联合在一起的查询的一个故意的特征是它们不能相互引用。您最好的选择是围绕您所拥有的内容包装更多sql 一种选择是添加另一列,可能称为source_id,然后使用窗口函数查找最低的source_id,然后使用该列进行过滤
然而,这意味着执行所有查询,并在所有结果之上运行一些处理。就我个人而言,我会使用plpgsql将结果插入临时表,对查询进行迭代,直到实际插入任何行。联合在一起的查询的一个故意的特点是它们不能相互引用。您最好的选择是围绕您所拥有的内容包装更多sql 一种选择是添加另一列,可能称为source_id,然后使用窗口函数查找最低的source_id,然后使用该列进行过滤
然而,这意味着执行所有查询,并在所有结果之上运行一些处理。就我个人而言,我会使用plpgsql insert结果将结果插入临时表,迭代查询,直到实际插入任何行。您可以执行条件联合:
with main as (
select house, street, town, 10 as weight
from addresses
where ...
)
select *
from main
union all
select *
from addresses
where ...
and not exists (select *
from main
limit 1);
子选择中的限制1可能不是必需的,因为Postgres查询规划器足够智能,但也不会有任何影响。您可以执行条件联合:
with main as (
select house, street, town, 10 as weight
from addresses
where ...
)
select *
from main
union all
select *
from addresses
where ...
and not exists (select *
from main
limit 1);
子选择中的限制1可能不是必需的,因为Postgres查询规划器足够智能,但也不会有任何影响。这对两个查询都可以,但如果我想添加更多,该怎么办?这对两个查询都可以,但如果我想添加更多呢?