Wasim
Wasim

Reputation: 5113

Re-using nested SQL statements within parent statement in MySQL

I have the following SQL code;

SELECT  a.*, b.maxDate as last_payment_date, c.package as payment_for_package, (SELECT COUNT(id) FROM uploads WHERE user = a.id) AS upload_count
                FROM users a 
                    INNER JOIN payments c
                        ON a.id = c.user_id
                    INNER JOIN
                    (
                        SELECT user_id, MAX(date) maxDate, period
                        FROM payments
                        GROUP BY user_id
                    ) b ON c.user_id = b.user_id AND
                            c.date = b.maxDate

                WHERE a.package = 1
                AND b.maxDate < $twomonths
                AND (SELECT COUNT(id) FROM uploads WHERE user = a.id) > 10
                AND b.period = 1
                ORDER BY b.maxDate ASC
                LIMIT 50

As you can see I use the nested statement (SELECT COUNT(id) FROM uploads WHERE user = a.id) twice and I was wondering if there is a way to re-use this statement for improved performance? I've tried using the alias upload_count but you can't use alias' in WHERE clauses. Appreciate the help

Upvotes: 2

Views: 160

Answers (1)

cdhowie
cdhowie

Reputation: 169143

Just join to the subquery and correlate the results:

SELECT
    a.*,
    b.maxDate as last_payment_date,
    c.package as payment_for_package,
    upload_counts.upload_count

FROM users a 

INNER JOIN payments c
    ON a.id = c.user_id

INNER JOIN
(
    SELECT user_id, MAX(date) maxDate, period
    FROM payments
    GROUP BY user_id
) b ON c.user_id = b.user_id AND
       c.date = b.maxDate

INNER JOIN
(
    SELECT user, COUNT(id) AS upload_count
    FROM uploads
    GROUP BY user
) upload_counts ON upload_counts.user = a.id

WHERE a.package = 1
AND b.maxDate < $twomonths
AND upload_counts.upload_count > 10
AND b.period = 1

ORDER BY b.maxDate ASC
LIMIT 50;

Upvotes: 3

Related Questions