微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – MySQL查询多个LEFT加入问题

我试图从以下查询获得所需的结果,但它似乎没有工作…

SELECT disTINCT
u.user_name as user_name,
u.total_points as total_points,
u.user_id as user_id,
COUNT(a.id) as user_total_articles_published,
COUNT(r.id) as user_total_replies_published,
COUNT(v.id) as user_total_Votes_done
FROM users as u
LEFT JOIN articles as a ON u.user_id=a.user_id
LEFT JOIN replies as r ON u.user_id=r.user_id
LEFT JOIN Votes as v ON u.user_id=v.user_id
GROUP BY u.user_id
ORDER BY u.total_points DESC
LIMIT 10

如果我删除最后2个LEFT jOINS,查询将起作用…其他2的错误是什么?我是否必须使用其他方法才能工作?

谢谢

解决方法:

我想通过’不工作’你的意思是查询返回太多记录?这是因为联接的组合.您将返回每篇文章记录的每个回复,因此数字会相乘.您可以通过在COUNT中使用disTINCT来解决此问题.这样,您可以计算唯一ID,因此您只需计算一次每篇文章

COUNT(distinct a.id) as user_total_articles_published,
COUNT(distinct r.id) as user_total_replies_published,
COUNT(distinct v.id) as user_total_Votes_done

[编辑]

一个可能更快的解决方案,无需disTINCT和GROUP BY:

SELECT
  u.user_name as user_name,
  u.total_points as total_points,
  u.user_id as user_id,
  (SELECT COUNT(a.id) FROM articles a 
   WHERE a.user_id = u.user_id) as user_total_articles_published,
  (SELECT COUNT(r.id) FROM replies r 
   WHERE r.user_id = u.user_id) as user_total_replies_published,
  (SELECT COUNT(v.id) FROM Votes v 
   WHERE v.user_id = u.user_id) as user_total_Votes_done
FROM users as u
ORDER BY u.total_points DESC
LIMIT 10

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐