SQL数据库SELECT JOIN查询

时间:2018-08-19 23:59:11

标签: sql

我可以用三个表来做这个问题。但是,多余的桌子让我很困惑。这是模式:

COURSE(CourseID, CourseName)
COURSEMODULES(CourseID, ModuleID)
MODULE (ModuleID, ModuleName, LecturerID)
LECTURER(LecturerID, FirstName, Surname, Email)

您如何确保不止一位讲师可以在一个模块上授课?

1 个答案:

答案 0 :(得分:0)

我对架构中包含的数据类型做了一些假设。以下查询将允许您仅选择正在教授多个模块的讲师:

SELECT
    COUNT(ModuleName) AS number_of_modules_taught
    , FirstName
    , Surname
    , Email
    , CourseName
FROM 
    (SELECT
        l.FirstName
        , l.Surname
        , l.Email
        , c.CourseName
        , m.ModuleName
    FROM course c
        JOIN coursemodules cm ON c.CourseID = cm.CourseID
        JOIN module m ON cm.ModuleID = m.ModuleID
        JOIN lecturer l ON m.LecturerID = l.lecturerID
    ) AS modules_by_lecturer
GROUP BY 2, 3, 4, 5

HAVING COUNT(ModuleName) > 1

我还在SQL Fiddle上提供了此功能,供您使用:http://sqlfiddle.com/#!9/9f25d5/4

编辑:在我看来,您实际上可能会真正关心将数据加载到表中,以便一位讲师可以映射到多个模块上。这可以通过允许ModuleID字段唯一,并将其​​映射到同一位讲师来实现:

CREATE TABLE course (CourseID VARCHAR(20), CourseName VARCHAR(100));
CREATE TABLE coursemodules (CourseID VARCHAR(20), ModuleID VARCHAR(20));
CREATE TABLE module (ModuleID VARCHAR(20), ModuleName VARCHAR(100), LecturerID VARCHAR(20));
CREATE TABLE lecturer (LecturerID VARCHAR(20), FirstName VARCHAR(50), Surname VARCHAR(50), Email VARCHAR(100));

INSERT INTO course (CourseID, CourseName) VALUES(12345, 'Pysics 101'),(23456, 'English 102'),(34567, 'Computer Science 306');
INSERT INTO coursemodules (CourseID, ModuleID) VALUES(12345, 13579),(12345, 79135),(23456, 35791),(34567, 57913);
INSERT INTO module (ModuleID, ModuleName, LecturerID) VALUES(13579, 'Newton\'s Laws', 24680),(79135, 'Thermodynamics', 24680),(35791, 'Chaucer', 46802),(57913, 'Lambda Functions in Java', 68024);
INSERT INTO lecturer (LecturerID, FirstName, Surname, Email) VALUES(24680, 'Stephen', 'Hawking', 'shawking@cambridge.com'), (80246, 'Neil', 'Tyson', 'ndtyson@amnh.org'),(46802, 'George', 'Martin', 'grrmartin@westeros.com'),(68024, 'Linus', 'Torvalds', 'lt@linux.org');