2009-08-20 68 views
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; 

回答

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
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 
+0

是啊,把我的意見了。 SRY。 – 2009-08-20 15:48:06

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;