有3个表:
CREATE TABLE Employee(
EID mediumint PRIMARY KEY AUTO_INCREMENT,
EName varchar(100) DEFAULT NULL,
EPincode mediumint unsigned NULL
);
EID是每个员工的唯一员工ID;
CREATE TABLE Project(
PID mediumint PRIMARY KEY AUTO_INCREMENT,
PName varchar(30) DEFAULT NULL,
MID mediumint UNIQUE NOT NULL,
FOREIGN KEY (MID) REFERENCES Employee(EID)
);
MID是负责项目的员工的Manager-Id。
CREATE TABLE Works_On(
EID mediumint NOT NULL,
PID mediumint NOT NULL,
FOREIGN KEY (EID) REFERENCES Employee(EID),
FOREIGN KEY (PID) REFERENCES Project(PID)
);
此表包含所有员工及其相关项目。
一个员工可以从事多个项目。一个项目可以通过 多名员工。每个项目都有一个经理。经理可以有一个 或更多在他之下的员工。
我想找到一个由员工姓名,项目名称和经理姓名组成的表。请帮忙。
这是我到目前为止编写的查询,但是不起作用:
SELECT DISTINCT A.EName AS "Employee Name"
,A.PName AS "Project Name"
,B.EName AS "Manager Name"
FROM (SELECT P.PName
,E.EName
from Works_On W
NATURAL JOIN Project P
NATURAL JOIN Employee E) A,
(SELECT E.EName
from Project P
INNER JOIN Employee E ON P.MID = E.EID) B
答案 0 :(得分:0)
您可以在下面的查询中尝试-
SELECT
E.EName,
P.PName,
M.EName
FROM Employee E
INNER JOIN Employee M ON M.EID = E.EID
INNER JOIN Project P ON E.EID = P.MID
INNER JOIN Works_On W ON W.EID = E.EID AND W.PID = P.PID
这可能会对您有所帮助。
答案 1 :(得分:0)
select A.Employee_name,
A.project_name,
B.manager_name from
(
SELECT
P.PName AS project_name,
E.EName AS Employee_name,
E.EID,P.PID
FROM Works_On W
INNER JOIN Project P ON W.PID = P.PID
INNER JOIN Employee E ON W.EID = E.EID
) as A
left join
(
SELECT
E.EName AS manager_name,
E.EID,P.PID
FROM Project P
INNER JOIN Employee E ON P.MID = E.EID
) B on A.PID=B.PID
答案 2 :(得分:0)
SELECT P.PName AS ProjectName,
M.EName AS ManagerName,
E.EName AS EmployeeName
FROM Project P
LEFT JOIN Employee M ON (P.MID=M.EID)
LEFT JOIN Works_On WO on (P.PID=WO.PID)
LEFT JOIN Employee E on (E.EID=WO.EID);
有效。