Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 使用子查询加快查询速度_Mysql - Fatal编程技术网

Mysql 使用子查询加快查询速度

Mysql 使用子查询加快查询速度,mysql,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 wher

下面是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
一种方法是使用外部应用/横向联接以避免重复子查询:

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;
也许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;

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

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

我已经删除了不相关的标签,再次重新标记您真正使用的标签。