使用子查询更快地进行查询

时间:2018-06-05 14:57:26

标签: mysql

我在下面有一个mysql查询,它从父表中选择行并获取子表的计数和总和。有没有办法提高绩效?

select
    parent.id,
    parent.date,
    parent.name,
    (select count(child.id) 
     from child 
     where child.parentid = parent.id) as count,
    (select sum(child.amount) 
     from child 
     where child.parentid = parent.id) as sum
from 
    parent

3 个答案:

答案 0 :(得分:1)

也许JOIN是一种有效的方法:

select p.id, p.date, p.name, c.count, c.sum
from parent p left join (
        select parentid , count(*) as count, sum(amount) as sum
        from child
        group by parentid 
       ) c on c.parentid = p.id;

答案 1 :(得分:0)

一种方法是使用OUTER APPLY/LATERAL JOIN来避免重复子查询:

select
  parent.id,
  parent.date,
  parent.name,
  sub.cnt,
  sub.total
from parent
OUTER APPLY (select count(child.id) AS cnt, sum(child.amount) AS total
             from child where child.parentid = parent.id) sub

刚看到MySQL标签:

SELECT parent.id,
  parent.date,
  parent.name,
  count(child.id) AS cnt,
  sum(child.amount) AS total
FROM parent
LEFT JOIN child 
  ON child.parentid = parent.id
GROUP BY parent.id, parent.date, parent.name;

答案 2 :(得分:0)

有时它会归结为尝试变更查询和评估执行计划,但如果当前查询计划正在为每个父记录执行查找,则执行左连接然后分组可能会更快。

SELECT p.id, p.[date], p.name, COUNT(c.id) AS childCount, SUM(c.amount) AS childSum
FROM parent AS p
LEFT JOIN child AS c ON c.parentid = p.id
GROUP BY p.id, p.[date], p.name