简体   繁体   中英

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. 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.

mysql specific links that confirm correaleated subqueries are not optimal choices in mysql. How to optimize Answer indicating msql notoriously bad at optimizing correlated subqueries

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. 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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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