稍微复杂的SQL查询

时间:2014-04-02 17:53:07

标签: mysql sql

编写一个SQL查询,按用户返回文章数量,如下列结果与列标题:' user_id',' username',' total_count_of_articles'按文章数量排序 enter image description here

1 个答案:

答案 0 :(得分:1)

这样的东西应该返回指定的结果集:

 SELECT u.id AS user_id
      , u.user_name
      , SUM(a.user_id IS NOT NULL) AS total_count_of_articles
   FROM users u
   LEFT
   JOIN users_articles a
     ON a.user_id = u.id
  GROUP BY u.id, u.user_name
  ORDER BY total_count_of_articles DESC