MySQL子查询减慢了“主”查询的速度

时间:2016-07-12 07:12:36

标签: mysql

谷歌和其他帖子对我帮助不大,或者我不能只是阅读。

获得此查询,该查询为我提供了每个ID的最新日志条目

select companies.id, companies.name, companies.email, tal1.content, tal1.created_at
from log_items tal1
inner join companies on companies.id = loggable_id
where tal1.loggable_id IN 
                        (
                            select companies.id
                            from companies
                            where companies.disabled = "3"
                        ) 
and tal1.created_at = (select max(tal2.created_at) from log_items tal2 where tal2.loggable_id = tal1.loggable_id);

问题是子查询会使查询变慢,以指向可以使用meme“ain't nobody got time for that”的位置。

子查询单独运行不到1秒。当ID直接给出时,“更大”的查询也会在一秒钟内运行,如:

select companies.id, companies.name, companies.email, tal1.content, tal1.created_at
            from log_items tal1
            inner join companies on companies.id = loggable_id
            where tal1.loggable_id IN 
(
"43c24b1d-cd48-4d3b-a75e-2de77a494ab9",
"c43b8c14-4593-4c3c-a383-e609003a09c8",
"5d559355-a4e0-4fea-9f50-fea1bbd8d011",
"f0ce61a2-d8d2-4651-ba12-a79f5515f527"
) 
and tal1.created_at = (select max(tal2.created_at) from log_items tal2 where tal2.loggable_id = tal1.loggable_id);

那么我做错了什么,或者有更好的方法来做那个子查询?不熟悉SQL。

1 个答案:

答案 0 :(得分:0)

试试这个:

select a.id, a.name, a.email, a.content, b.created_at  from
(select companies.id, companies.name, companies.email, tal1.content, tal1.created_at  from
(select companies.id, companies.name, companies.email, tal1.content, tal1.created_at  from log_items tal1) as tal1
left JOIN
(select id, name,email from companies) as companies
on companies.id = tal1.loggable_id
 where tal1.loggable_id IN 
(
"43c24b1d-cd48-4d3b-a75e-2de77a494ab9",
"c43b8c14-4593-4c3c-a383-e609003a09c8",
"5d559355-a4e0-4fea-9f50-fea1bbd8d011",
"f0ce61a2-d8d2-4651-ba12-a79f5515f527"
)) as a
left join
(select tal1.content, tal1.created_at from 
 (select content,created_at from log_items) as   tal1
left JOIN
(select max(created_at) as created_at_max from log_items tal2) as tal2
on  where tal2.loggable_id = tal1.loggable_id) as b

on a.created_at = b.created_at