2

私は次のSQLコードを持っています。

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

ご覧のとおり、ネストされたステートメントを(SELECT COUNT(id) FROM uploads WHERE user = a.id)2回使用していますが、パフォーマンスを向上させるためにこのステートメントを再利用する方法があるかどうか疑問に思っていました。エイリアスを使用してみましたが、句upload_countで「エイリアス」を使用できません。WHEREヘルプに感謝します

4

1 に答える 1

3

サブクエリに参加して、結果を相互に関連付けます。

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;
于 2012-09-21T15:43:32.893 に答える