我有一个左连接到一个表,并希望在按父表的列分组后计算它的列:
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
哪种解决方案最好?
答案 0 :(得分:1)
查询2和3中缺少成员的别名m
。否则,它们应该给出相同的数字。
查询2(已修复)将执行得最快。
查询1的不同之处在于,如果每个uploads
有多个lists
的情况,它会为member
提供更高的数字。加入lists
后,成员也会有多行,这会增加uploads
的计数。所以查询1可能是错误的。
此外,NULL
值不计算。 manual informs:
COUNT(表达式)
返回行中expr的非NULL值的数量 由SELECT语句检索。结果是BIGINT值。