views:

365

answers:

3

How do I change the following dependent subquery to 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;
+1  A: 
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
chaos
`@Arpit`: it is correct when `uid` is a `PRIMARY KEY`, however, the `JOIN` is redundant in this case.
Quassnoi
yeah, took my comment back. sry.
Arpit Tambi
+3  A: 
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

If uid is a PRIMARY KEY, you can rewrite it like this:

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
Quassnoi
A: 
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;
Arpit Tambi