依赖子查询自连接

时间:2009-08-20 14:29:55

标签: mysql subquery inner-join self-join

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

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; 

3 个答案:

答案 0 :(得分: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

如果uidPRIMARY 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

答案 1 :(得分: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

答案 2 :(得分: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;