douxian6086 2011-09-15 14:43
浏览 55
已采纳

MySQL查询多个LEFT加入问题

I am trying to get the required result from the following query but it doesnt seem to work...

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

If i remove the last 2 LEFT jOINS the query will work... whats wrong with the other 2? Do i have to use another method for this to work?

thanks

  • 写回答

1条回答 默认 最新

  • duan19740319 2011-09-15 14:46
    关注

    I think by 'not working' you mean that the query returns too many records? That is because of the combination of joins. You return each reply for each article record, so the numbers are multiplied. You can solve this by using DISTINCT in the COUNT. That way, you count the unique id's, so you count each article only once:

    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
    

    [edit]

    A possibly faster solution, eliminating the need for DISTINCT and 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题