MySQL留下了连接数

时间:2011-10-15 14:53:12

标签: mysql sql count left-join

我有一个左连接到一个表,并希望在按父表的列分组后计算它的列:

SELECT * , COUNT(list.id) AS listcount, COUNT(uploads.id) AS uploadcount 
FROM members 
LEFT JOIN lists ON members.id= list.mid
LEFT JOIN uploads ON members.id= uploads.mid
GROUP BY members.id

假设用户可以根据用户类型进行列表或上传。那么上面的查询足够好吗?如果不是为什么?

或者我必须使用此查询吗?

SELECT * , l.listcount,   u.uploadcount 
FROM members 
LEFT JOIN (select count(lists.id) as listscount,mid from lists group by mid) as l
                                                                on l.mid = m.id
LEFT JOIN (select count(uploads.id) as uploadscount
                           ,mid from uploads group by mid) as u on u.mid = m.id
GROUP BY members.id

或相关子查询?

SELECT *,
      (select count(lists.id) as listscount from lists as l where l.mid = m.id
       group by mid) as listcount
      (select count(uploads.id) from uploads as u where u.mid = m.id
       group by mid) as uploadscount 
FROM members 
GROUP BY members.id

哪种解决方案最好?

1 个答案:

答案 0 :(得分:1)

查询2和3中缺少成员的别名m。否则,它们应该给出相同的数字。

查询2(已修复)将执行得最快。

查询1的不同之处在于,如果每个uploads有多个lists的情况,它会为member提供更高的数字。加入lists后,成员也会有多行,这会增加uploads的计数。所以查询1可能是错误的

此外,NULL计算。 manual informs

  

COUNT(表达式)

     

返回行中expr的非NULL值的数量   由SELECT语句检索。结果是BIGINT值。