MySQL 左连接计数
我有一个到表的左联接,并希望在按父表的列分组后计算其中的列数:
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
哪个是最好的解决方案?
I have a left join to a table and want to count columns from it, after grouping by a column of the parent table:
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
Assume that a user can have either lists or uploads based on the type of user. Then is above query good enough? If not why?
Or do I have to use this query?
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
Or correlated subqueries?
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
And which is best solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查询 2 和 3 中缺少成员的别名
m
。否则它们应该给出相同的数字。查询 2(已修复)的执行速度最快。
查询 1 的不同之处在于,如果每个
成员
有多个列表
,它将给出更高的上传
数量。加入列表
后,成员也会有多行,这会增加上传
的计数。因此查询 1 可能是错误的。此外,
NULL
值也不计算在内。 手册告知:The alias
m
for members is missing in query 2 and 3. Otherwise they should give the same numbers.Query 2 (fixed) will perform fastest.
Query 1 is different in that it will give a higher number for
uploads
, if there are cases of multiplelists
permember
. After joining tolists
, there will be multiple rows for a member too, which will increase the count foruploads
. So query 1 is probably wrong.Also,
NULL
values are not counted. The manual informs: