Skip to content
Advertisement

how can i optimize this mysql statement, it is very slow

Advertisement

Answer

This query is slow because it is actually 16 x 3 = 48 queries. You have 16 SELECT correlated subqueries in your main SELECT query, and you’re looking up three values of p._id.

Your first step is to transform at least some of those subqueries into independent subqueries and JOIN them. (This is a vital skill for people who use SQL.)

I’ll show you how to refactor a couple of them.

First, the easy one — the post title. Just LEFT JOIN your posts_log table to your profile_details table ON the appropriate id values.

Next, let us write a subquery to retrieve your your regs column in your result set. This aggregating (GROUP BY) subquery generates the regs value for each value of _id_2 in the table.

Then you LEFT JOIN that subquery in your main query, and SELECT the result.

That’s the pattern to use.

(I am confused about whether your _id values start with underscores or not. You didn’t show us your table definitions so it’s hard for me to get that right. Also, I assume the ${ date_range ... } stuff expands to a valid SQL date-range filter.)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement