合并表并按升序获取输出

时间:2017-09-07 21:11:54

标签: mysql sql

我有两张桌子:

student                                   department
id  department_id                      department_id  department_name

5     5                                  5              Computer Science
1     4                                  4              Architecture
3     2                                  1              Mathematics
4     5                                  3              Chemistry
2     4                                  2              Physics

我写了一个如下查询,得到了以下结果。

SELECT DEPARTMENTS.DEPT_NAME AS D, STUDENTS.DEPT_ID AS D_ID
FROM STUDENTS 
INNER JOIN DEPARTMENTS
ON STUDENTS.DEPT_ID=DEPARTMENTS.DEPT_ID ;



Computer Science 5
Computer Science 5
Physics 2
Architecture 4
Architecture 4

直到这里它很好,但我想要像

这样的东西
Computer Science 2
Architecture 2
Physics 1
Chemistry 0
Mathematics 0

,即部门名称,num_of学生,其中num_of学生处于降序。

我可以在查询中添加什么内容?

5 个答案:

答案 0 :(得分:2)

我会使用COUNT(*)并将其子查询为ORDER BY

SELECT * FROM (
SELECT DEPARTMENTS.DEPT_NAME, COUNT(*) AS num_ofstudents
FROM STUDENTS 
LEFT JOIN DEPARTMENTS
ON STUDENTS.DEPT_ID=DEPARTMENTS.DEPT_ID
GROUP BY Departments.Dept_name
) AS a ORDER BY num_ofstudents

编辑 - 感谢AaronDietz指出这一点! 您应该将INNER JOIN替换为LEFT JOIN,以便查询中包含来自[部门]但没有任何学生的记录。此外,我不需要包含子查询。

SELECT DEPARTMENTS.DEPT_NAME, COUNT(*) AS num_ofstudents
FROM STUDENTS 
LEFT JOIN DEPARTMENTS
ON STUDENTS.DEPT_ID=DEPARTMENTS.DEPT_ID
GROUP BY Departments.Dept_name
ORDER BY num_ofstudents

答案 1 :(得分:1)

您可以尝试对部门和ID进行分组,然后计算。

SELECT DEPARTMENTS.DEPT_NAME AS D, COUNT(*) as NID
FROM STUDENTS 
INNER JOIN DEPARTMENTS
ON STUDENTS.DEPT_ID=DEPARTMENTS.DEPT_ID 
GROUP BY DEPARTMENTS.DEPT_NAME
ORDER BY NID DESC

答案 2 :(得分:1)

我认为最简单的方法是选择部门并在子查询中获取计数:

select
  d.department_id,
  d.department_name,
  colalesce(s.students, 0) as student_count,
  s.ids as student_ids
from department d
left join
(
  select 
    department_id,
    count(*) as students,
    group_concat(id) as ids
  from student
  group by department_id
) s on s.department_id = d.department_id
order by 3 desc;

这很有效,因为你只需要学生中的一个值,即计数。如果您想要更多信息,那么您可以将子查询移动到from子句。 E.g:

.button { color: red; }

答案 3 :(得分:0)

SELECT DEPARTMENTS.DEPT_NAME AS D, count(STUDENTS.DEPT_ID) AS D_ID
FROM STUDENTS 
INNER JOIN DEPARTMENTS
ON STUDENTS.DEPT_ID=DEPARTMENTS.DEPT_ID
GROUP BY D
ORDER BY D_ID DESC;

答案 4 :(得分:0)

按部门名称分组
其他查询大多是正确的,但COUNT应该是学生ID,查询应该从department而不是student开始。

SELECT DEPARTMENTS.DEPT_NAME, 
       COUNT(id) AS num_ofstudents
FROM DEPARTMENT 
LEFT JOIN students ON STUDENTS.DEPT_ID = DEPARTMENTS.DEPT_ID
GROUP BY DEPARTMENTS.DEPT_NAME
ORDER BY num_ofstudents