简体   繁体   English

MySQL选择使用组和计数连接表

[英]MySQL select using group and count for join tables

For my project, I've a student table and a school table. 对于我的项目,我有一张学生桌和一张学校桌子。

A student belongs to a company. 学生属于公司。 A school has many students. 一所学校有很多学生。

(A student's school_id is assigned NULL when that student graduates.) (当学生毕业时,学生的school_id被指定为NULL。)

The student table:
+----+------------+-----------+------------+
| id | first_name | last_name | school_id  |
+----+------------+-----------+------------+
The school table:
+----+------------+------------------------+
| id | city_id    | name                   |
+----+------------+------------------------+

The goal is to inner join these tables, count the students for each school, and order by the student number. 目标是内部加入这些表格,计算每所学校的学生数量,并按学生编号进行排序。

Consider following SQL query: 考虑以下SQL查询:

SELECT school.NAME, 
       count(student.id) AS Total_Student 
FROM   school 
       LEFT JOIN student 
              ON school.id = student.school_id 
GROUP BY school.id
ORDER BY Total_Student

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM