简体   繁体   English

查询执行时间慢

[英]Slow query execution time

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 

This query took about 0.2407s to execute. 该查询大约花费0.2407s来执行。 How to make it fast? 如何使其快速?

Correlated subqueries can have subpar performance as they are executed row by row. 关联的子查询在逐行执行时可能具有低于标准的性能 To solve this move your correlated subquery into a regular subquery/derived table and join to it. 要解决此问题,请将您的相关子查询移到常规子查询/派生表中并加入其中。 It will then not have execute row by row for the entire returned result set as it will be executed BEFORE the select statement. 这样,它将不会在整个返回结果集中逐行执行代码,因为它将在select语句之前执行。

mysql specific links that confirm correaleated subqueries are not optimal choices in mysql. 确认相关子查询的mysql特定链接不是mysql中的最佳选择。 How to optimize Answer indicating msql notoriously bad at optimizing correlated subqueries 如何优化 Answer指示msql非常不利于优化相关子查询

I use sql-server, but I'm sure the principle is the same for mysql , so I hope this at least points you in the right direction. 我使用sql-server,但是我确定mysql的原理是相同的 ,因此我希望这至少可以为您指明正确的方向。 You would need to partition/return your one result per loan, maybe some could chime in on mysql specific syntax and I could update my answer 您将需要对每笔贷款进行分区/返回结果,也许有些可能会干扰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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM