加入MySQL的声明

时间:2010-11-10 03:46:53

标签: sql mysql select join

我有一个包含以下表格的MySQL数据库:

Table: Professor
Attributes: ID, ProfessorName

Table: Class
Attributes: ID, ClassName, SubjectID (secondary)

Table: Subject
Attributes: ID, SubjectName

Table: DocCategory
Attributes: ID, DocCategoryName

Table: Document
Attributes: ID, DocName, ProfessorID (secondary), ClassID (secondary), DocCategoryID (secondary)

有人可以通过查询向我指出正确的方向,以便获得包含以下内容的报告:

所有ProfessorName的列表,第二列包含与该教授相关的文档表中的文档计数?

提前致谢!

1 个答案:

答案 0 :(得分:4)

使用:

  SELECT p.professorname,
         COUNT(*) AS numDocuments
    FROM PROFESSOR p
    JOIN DOCUMENT d ON d.professorid = p.id
GROUP BY p.professorname

要查看所有教授的列表 - 没有文档的人将列出零值 - 使用:

   SELECT p.professorname,
          COALESCE(COUNT(d.id), 0) AS numDocuments
     FROM PROFESSOR p
LEFT JOIN DOCUMENT d ON d.professorid = p.id
 GROUP BY p.professorname