开发者

Joining tables and aggregating data in MySQL?

I have 2 tables. Members and their projects. I need to extract all the users, with the number of their projects, sorted by the number of projects.

Table: users:

id | username | email | password | reg_date

Table: projects:

id | title    | descr | a开发者_如何学运维utor

For the join:

projects.autor = users.id


SELECT
  users.id,
  users.username,
  COUNT(projects.id) AS `num_projects`
FROM
  users
LEFT OUTER JOIN
  projects
ON
  projects.autor = users.id
GROUP BY
  users.id
ORDER BY
  num_projects DESC


SELECT u.id AS id, u.username AS username, u.email AS email, u.password AS password, u.reg_date AS reg_date, COUNT(p.id) AS projects_count 
FROM users u
LEFT OUTER JOIN projects p ON p.autor = u.id
GROUP BY u.id 
ORDER BY projects_count DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜