在尝试将以下两个查询优化为一个查询时,我遇到了一个问题。
结果1:
select *
from sip_trunks
where resporg_account_id_id=62
and identifier = (select action
from sip_trunk_numbers
where number='xxxxxxxxxx'
and resporg_id=80 limit 1)
limit 1结果2:
select *
from sip_trunks
where resporg_account_id_id=62
and sip_trunks.default=true
limit 1最终输出=结果1+结果2
到目前为止,我已经做到了这一点。
注意:我不能执行UNION,因为我不确定RESULT 1是否会产生任何结果(因此在下面的查询中使用了matcher标志。除了检查返回的行外,我知道结果2将始终存在。
select *,
(case
when identifier=(select action from sip_trunk_numbers where number='xxxxxxxxxx' and resporg_id=80 limit 1)
then 1
when sip_trunks.default=true
then 2
else 3
end) as matcher
from sip_trunks
where resporg_account_id_id=62
order by matcher asc
limit 2;现在我被困住了。
答:我不能根据比赛结果分组,因为Postgres抱怨组中没有使用“*”。
但是首先,我不确定子查询是(select action from sip_trunk_numbers where number='xxxxxxxxxx' and resporg_id=80 limit 1)有多坏
使用子查询作为列将使其对所有行运行,或者对where条件匹配的行运行。
换句话说,子查询是对sip_trunks的所有行运行,还是只对resporg_account_id_id=62匹配的行运行。
发布于 2019-08-14 07:08:58
为什么不使用OR条件呢?
select *
from sip_trunks
where resporg_account_id_id = 62
and ( sip_trunks.default = true
or identifier = (select action
from sip_trunk_numbers
where number = 'xxxxxxxxxx'
and resporg_id = 80
limit 1))
limit 1如果需要知道匹配的条件,可以使用UNION:
select *
from (
select st.*, 1 as source
from sip_trunks st
where resporg_account_id_id = 62
and identifier = (select action
from sip_trunk_numbers
where number = 'xxxxxxxxxx'
and resporg_id = 80
limit 1)
limit 1
union all
select st.*, 2 as source
from sip_trunks st
where resporg_account_id_id = 62
and sip_trunks.default = true
limit 1
)
order by source
limit 1如果source等于结果中的1,则第一个查询匹配,否则为第二个。
或者,您可以使用外部连接:
select st.*,
stn.action is not null as identifier_matched
from sip_trunks st
left join (
select action
from sip_trunk_numbers
where number = 'xxxxxxxxxx'
and resporg_id = 80
limit 1
) stn on stn.action = st.identifier
where resporg_account_id_id = 62
and (stn.action is not null or sip_trunks.default = true)
limit 1注意,没有订单的limit通常是没有意义的。
https://dba.stackexchange.com/questions/245288
复制相似问题