我有2张桌子。会员及其项目。我需要提取所有用户,他们的项目数量,按项目数量排序。
表:users
:
id | username | email | password | reg_date
表:projects
:
id | title | descr | autor
对于加入:
projects.autor = users.id
答案 0 :(得分:1)
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
答案 1 :(得分:1)
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