1

如何将以下依赖子查询更改为自联接?

SELECT d.name, d.created,   
(SELECT SUM( q1.payout ) FROM client AS q1 WHERE q1.uid = d.uid) AS payout,   
(SELECT COUNT( q2.uid ) FROM client AS q2 WHERE q2.uid = d.uid AND q2.winning =1) AS cnt   
FROM client AS d group by d.name, d.created  ORDER BY cnt DESC   LIMIT 0 , 10; 
4

3 回答 3

3
SELECT  d.name, d.created, SUM(q1.payout) AS psum, COUNT(q2.uid) AS cnt
FROM    client d
LEFT JOIN
        client q1
ON      q1.uid = d.uid
LEFT JOIN
        client q2
ON      q2.uid = d.uid
        AND q2.winning =1
GROUP BY
        d.name, d.created
ORDER BY
        cnt DESC
LIMIT 0, 10

如果uid是 a PRIMARY KEY,您可以像这样重写它:

SELECT  d.name, d.created, SUM(payout) AS psum, COUNT(IF(winning = 1, uid, NULL)) AS cnt
FROM    client d
GROUP BY
        d.name, d.created
ORDER BY
        cnt DESC
LIMIT 0, 10
于 2009-08-20T14:35:28.413 回答
1
SELECT d.name, d.created, SUM(d.payout) AS allpayout, COUNT(alt.uid) as cnt
FROM client AS d
LEFT JOIN client AS alt
ON alt.uid = d.uid AND alt.winning = 1
GROUP BY d.name, d.created
ORDER BY cnt DESC
LIMIT 0, 10
于 2009-08-20T14:34:54.030 回答
0
SELECT d.name, d.created, SUM( d.payout ) AS payout, SUM( IF( d.winning = 1, 1, 0 ) ) AS cnt
FROM client AS d
GROUP BY
    d.name, d.created
ORDER BY cnt DESC   LIMIT 0 , 10;
于 2009-08-20T14:42:24.050 回答