单个查询中的MySQL多计数

时间:2010-02-19 22:19:13

标签: mysql sql count

我试图在一个查询中计算两列,但结果是为medcount和uploadcount分配相同的值。有什么建议吗?

SELECT * , COUNT($tbl_list.listname) AS listcount, 
                    COUNT($tbl_uploads.id) AS uploadcount 
        FROM $tbl_members 
        LEFT JOIN $tbl_list ON $tbl_members.username = $tbl_list.username 
        LEFT JOIN $tbl_uploads ON $tbl_members.username = $tbl_uploads.username 
        GROUP BY $tbl_members.username 
        ORDER BY $tbl_members.lastname, $tbl_members.firstname;

1 个答案:

答案 0 :(得分:7)

使用:

   SELECT tm.*, 
          x.listcount, 
          y.uploadcount 
     FROM $tbl_members tm 
LEFT JOIN (SELECT tl.username,
                  COUNT(tl.listname) AS listcount
             FROM $tbl_list tl
         GROUP BY tl.username) x ON x.username = tm.username
LEFT JOIN (SELECT tu.username,
                  COUNT(tu.id) AS uploadcount
             FROM $tbl_uploads tu
         GROUP BY tu.username) y ON y.username = tm.username
 GROUP BY tm.username 
 ORDER BY tm.lastname, tm.firstname