简体   繁体   English

Mysql 如何合并不同表的数据

[英]Mysql how to combine data from different tables

EER图

The question is问题是

"display the professor name and the number of students he/she is mentoring. Sort the output by the professor name." “显示教授姓名和他/她指导的学生人数。按教授姓名对 output 进行排序。”

If you refer to the EER diagram, ProfessorName is in the professor table while the data needed to count the amount of students a professor is mentoring is in the student_professor table.如果您参考 EER 图,ProfessorName 在教授表中,而计算教授指导的学生数量所需的数据在 student_professor 表中。 What's the statement to display this?显示这个的语句是什么?

the best I could come up with is我能想到的最好的就是

SELECT
  ProfessorName,
  COUNT (*)
FROM  professor
WHERE ProfessorId IN
  (SELECT
      ProfessorId,
      COUNT (*)
     FROM student_professor
     WHERE Mentor = 1
  GROUP BY ProfessorId);

You can use this query.您可以使用此查询。

SELECT p.ProfessorName, COUNT(sp.StudentNo)
FROM professor p
LEFT JOIN student_professor sp ON p.ProfessorId = sp.ProfessorId
WHERE sp.Mentor = 1
GROUP BY p.ProfessorId;

If you have different Professors with the same ProfessorName , then there will be duplicate ProfessorName in the result.如果您有不同的教授具有相同的ProfessorName ,那么结果中将会有重复的ProfessorName But the number of Students that is mentored by that Professor will still be exact because we're counting and grouping by the Primary Key of the Professor table, which is ProfessorId .但是,由该教授指导的学生数量仍然是准确的,因为我们正在按教授表的主键进行计数和分组,即ProfessorId

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

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