为什么合并计数查询执行时间太长?

时间:2019-12-14 12:22:40

标签: mysql

服务器不会在此查询中字节化,执行时间太长:

select prodavac.id, count(artikl.id) as brojartikala, count(poruceno.id) as brojporudzbina from prod_prodavac prodavac 
inner join prod_artikl artikl 
    on prodavac.id=artikl.prodavacid 
inner join prod_poruceno poruceno 
    on prodavac.id=poruceno.prodavacid 
group by prodavac.id 

另一方面,两个半查询都可以快速运行:

select prodavac.id, count(artikl.id) as brojartikala from prod_prodavac prodavac 
inner join prod_artikl artikl 
    on prodavac.id=artikl.prodavacid 
group by prodavac.id 

另外一个:

select prodavac.id, count(poruceno.id) as brojporudzbina from prod_prodavac prodavac 
inner join prod_poruceno poruceno 
    on prodavac.id=poruceno.prodavacid 
group by prodavac.id 
order by prodavac.id asc 

我真的很想在一个查询中做到这一点,那么如何以正确的方式合并它们呢?所有ID均为索引整数。

解释选择显示以下内容:

enter image description here

1 个答案:

答案 0 :(得分:1)

根据表和数据之间的关系,组合的查询甚至可能不会返回所需的结果。对于简单的关系计数,可以在SELECT子句中使用相关子查询:

select prodavac.id, (
    select count(*)
    from prod_artikl artikl 
    where artikl.prodavacid = prodavac.id
  ) as brojartikala, (
    select count(*)
    from prod_poruceno poruceno 
    where poruceno.prodavacid = prodavac.id
  ) as brojporudzbina
from prod_prodavac prodavac
order by prodavac.id asc