我在过去几天一直在尝试写一个执行以下操作的MySQL查询:
对于每个至少有一名合格教授教授课程的班级,列出有资格教授班级的教授人数。
我尝试了以下查询,但它没有提供正确的输出
select Class, Semester, p.EmpId from Qualified q, Teaches T, Professor p where q.EmpId = p.EmpId and T.EmpId = p.EmpId group by p.EmpId;
+-------+---------+-------+---------+-----------+------+-----------------------------------+
| EmpId | ClassId | EmpId | FName | LName | Dept | QualClass |
+-------+---------+-------+---------+-----------+------+-----------------------------------+
| 101 | BA101 | 101 | Bobby | Ewing | BA | BA101, BA102 |
| 102 | BA101 | 102 | Red | Skeleton | BA | BA101, BA102 |
| 101 | BA102 | 101 | Bobby | Ewing | BA | BA101, BA102 |
| 102 | BA102 | 102 | Red | Skeleton | BA | BA101, BA102 |
+-------+---------+-------+---------+-----------+------+-----------------------------------+
这些是相关表格。
CREATE TABLE Professor
(
EmpId INTEGER,
FName VARCHAR(10),
LName VARCHAR(10),
Dept VARCHAR(2),
QualClass VARCHAR(40),
PRIMARY KEY (EmpId)
);
CREATE TABLE Teaches
(
Class VARCHAR(5),
Section INTEGER,
Semester CHAR(4),
EmpId INTEGER,
FOREIGN KEY (EmpId) REFERENCES Professor(EmpId)
);
CREATE TABLE Qualified
(
EmpId INTEGER,
ClassId VARCHAR(5)
);
以下是一些DML语句
INSERT INTO Professor (EmpId, FName, LName, Dept, QualClass) VALUES (101, 'Bobby', 'Ewing', 'BA', 'BA101, BA102');
INSERT INTO Professor (EmpId, FName, LName, Dept, QualClass) VALUES (102, 'Red', 'Skeleton', 'BA', 'BA101, BA102');
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA101', 1, 'FA12', 101);
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA101', 1, 'SP13', 102);
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA101', 1, 'SU13', 101);
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA102', 1, 'FA12', 102);
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA102', 1, 'SP13', 101);
INSERT INTO Teaches (Class, Section, Semester, EmpId) VALUES ('BA102', 1, 'SU13', 102);
INSERT INTO Qualified (ClassId, EmpId) VALUES ('BA101', 101);
INSERT INTO Qualified (ClassId, EmpId) VALUES ('BA101', 102);
INSERT INTO Qualified (ClassId, EmpId) VALUES ('BA102', 101);
INSERT INTO Qualified (ClassId, EmpId) VALUES ('BA102', 102);
答案 0 :(得分:0)
根据您的陈述:
对于每个至少有一名合格教授教授课程的班级,列出有资格教授班级的教授人数。
以下查询列出有资格教授课程的教授人数。这里有一个SQLFiddle来展示它的作用:
SELECT Q.ClassId, count(Q.EmpId) as "Professor Count"
FROM Qualified Q
GROUP BY ClassId
现在,如果您还需要知道哪些教授是合格的,那将是不同的查询。