首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL查询的计算方法

SQL查询的计算方法
EN

Database Administration用户
提问于 2019-08-14 06:46:34
回答 1查看 59关注 0票数 0

在尝试将以下两个查询优化为一个查询时,我遇到了一个问题。

结果1:

代码语言:javascript
复制
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:

代码语言:javascript
复制
select * 
from sip_trunks 
where resporg_account_id_id=62 
and sip_trunks.default=true 
limit 1

最终输出=结果1+结果2

到目前为止,我已经做到了这一点。

注意:我不能执行UNION,因为我不确定RESULT 1是否会产生任何结果(因此在下面的查询中使用了matcher标志。除了检查返回的行外,我知道结果2将始终存在。

代码语言:javascript
复制
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匹配的行运行。

EN

回答 1

Database Administration用户

回答已采纳

发布于 2019-08-14 07:08:58

为什么不使用OR条件呢?

代码语言:javascript
复制
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:

代码语言:javascript
复制
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,则第一个查询匹配,否则为第二个。

或者,您可以使用外部连接:

代码语言:javascript
复制
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通常是没有意义的。

票数 1
EN
页面原文内容由Database Administration提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://dba.stackexchange.com/questions/245288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档