查询执行时间慢

时间:2012-03-21 05:24:20

标签: mysql sql

SELECT p.id, 
       p.title, 
       p.slug, 
       p.content, 
       (SELECT url 
        FROM   gallery 
        WHERE  postid = p.id 
        LIMIT  1) AS url, 
       t.name 
FROM   posts AS p 
       INNER JOIN termrel AS tr 
         ON ( tr.object = p.id ) 
       INNER JOIN termtax AS tx 
         ON ( tx.id = tr.termtax_id ) 
       INNER JOIN terms AS t 
         ON ( t.id = tx.term_id ) 
WHERE  tx.taxonomy_id = 3 
       AND p.post_status IS NULL 
ORDER  BY t.name ASC 

此查询执行大约需要0.2407秒。如何让它快速?

1 个答案:

答案 0 :(得分:0)

相关子查询的性能可以低于executed row by row. 要解决此问题,请将相关子查询移动到常规子查询/派生表中并加入其中。然后,它将不会逐行执行整个返回的结果集,因为它将在select语句之前执行。

确认已更正的子查询的mysql特定链接不是mysql中的最佳选择。 How to optimize Answer indicating msql notoriously bad at optimizing correlated subqueries

我使用的是sql-server,但我确定mysql的原理是相同的,所以我希望这至少可以指出你正确的方向。你需要为每个贷款分配/返回你的一个结果,也许有些人可以使用mysql特定的语法,我可以更新我的答案

select
    p.id
   ,p.title
   ,p.slug
   ,p.content
   ,t.name
   ,mySubQuery.value
from
    posts as p
    inner join termrel as tr
    on ( tr.object = p.id )
    inner join termtax as tx
    on ( tx.id = tr.termtax_id )
    inner join terms as t
    on ( t.id = tx.term_id )

    left join (
                -- use MYSQL function to partition the reslts and only return 1, I use sql-server, not sure of the RDMS specific syntax
                select
                id
                ,url
                from
                    gallery
                limit 1
              ) as mySubquery
    on mySubquery.id = p.id


where
    tx.taxonomy_id = 3
    and p.post_status is null
order by
    t.name asc