MySQL查询多个LEFT加入问题

时间:2011-09-15 14:43:04

标签: php mysql sql

我正在尝试从以下查询中获取所需的结果,但它似乎无法正常工作......

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的错误是什么?我是否必须使用其他方法才能工作?

感谢

1 个答案:

答案 0 :(得分:7)

我认为'不工作'你的意思是查询返回的记录太多了?这是因为联接的组合。您将返回每篇文章记录的每个回复,因此数字会相乘。您可以使用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