简体   繁体   中英

Is there a more efficient solution for this MySQL Query?

I am working on extracting and displaying data from a Wordpress DB to a mobile app for a customer and I am having a little trouble refining this query to be most efficient.

In wordpress, there are three tables that link the data I need to access 1. wp_posts - in this table there is the main post title, it's published status and the post type. 2. wp_postmeta - this table has all supplemental info related to the post id in the above table. 3. wp_p2p - this table has links to all the parent-child posts and their relationship.

Because of the volume of data in these tables, the query I currently have takes about 13 seconds to run, could you please take a look at this sqlfiddle and let me know what I could look at to improve it? The query in it's current form is not the end result, but improving it will improve my end result. I also need to add a search field on the "name" in the wp_postmeta table.

http://sqlfiddle.com/#!2/0e9e0/1

Any direction is appreciated, thank you!

If I understand correctly, you're looking for only child posts, in which case, the query below should be much faster:

SELECT wp_posts.id,  post_title, post_status, post_type
FROM wp_posts
JOIN wp_postmeta ON (wp_posts.id = wp_postmeta.post_id)
LEFT JOIN wp_p2p ON (wp_posts.id = wp_p2p.p2p_from)
WHERE `post_status`='publish' AND `post_type`='merchant' 
AND wp_p2p.p2p_from IS NULL
GROUP BY wp_posts.id

This query will be optimized to find where a match doesn't exist in the p2p table so that part will be much faster than how you're currently doing it. It looks like you can also remove the JOIN on wp_postmeta since you don't use it at all. Removing that JOIN would also make the GROUP BY redundant and removing it could help the performance a little. Removing the GROUP BY would also be a good practice since strictly you can't select non-aggregate fields that aren't in the GROUP BY clause, but MySQL provides for this functionality so the query will still work either way.

To begin with, you should join tables using INNER or OUTER JOIN syntax. So:

FROM wp_posts INNER JOIN wp_postmeta ON wp_posts.id = wp_postmeta.post_id

or perhaps you want an OUTER JOIN here?

Can you explain why you're doing a GROUP BY on wp_posts.id. Does this column not have unique values?

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