我有一个问题,我需要为位于斯塔福德的每个项目选择项目编号,控制部门编号,部门经理的Lname,地址和生日。我无法获得我想要的结果。
我试过了:
SELECT PROJECT.PNUMBER, PROJECT.DNUM, EMPLOYEE.LNAME, EMPLOYEE.ADDRESS, EMPLOYEE.BDATE
FROM PROJECT, EMPLOYEE, DEPARTMENT
WHERE PLOCATION = 'STAFFORD' AND DEPARTMENT.MGRSSN = EMPLOYEE.SSN;
得到了:
+---------+------+---------+-------------------------+-----------+ | PNUMBER | DNUM | LNAME | ADDRESS | BDATE | | 30 | 4 | WONG | 683 VOSS, HOUSTON, TX | 08-DEC-55 | | 10 | 4 | WONG | 683 VOSS, HOUSTON, TX | 08-DEC-55 | | 30 | 4 | WALLACE | 291 BERRY, BELLAIRE, TX | 20-JUN-41 | +---------+------+---------+-------------------------+-----------+
但我应该得到的是(或我想要的):
+---------+------+---------+-------------------------+-----------+ | PNUMBER | DNUM | LNAME | ADDRESS | BDATE | | 10 | 4 | WALLACE | 391 BERRY, BELLAIRE, TX | 20-JUN-41 | | 30 | 4 | WALLACE | 291 BERRY, BELLAIRE, TX | 20-JUN-41 | +---------+------+---------+-------------------------+-----------+
任何人都可以帮我弄清楚我的sql语句有什么问题吗? 抱歉,我无法弄清楚如何格式化
答案 0 :(得分:4)
基本上,您错过了DEPARTMENT
和PROJECT
上的加入。
我使用显式连接而不是过时的where
语法:
select
PROJECT.PNUMBER,
PROJECT.DNUM,
EMPLOYEE.LNAME,
EMPLOYEE.ADDRESS
-- and so on with the EMPLOYEE fields
from
PROJECT
inner join
DEPARTMENT
on DEPARTMENT.DNUMBER = PROJECT.DNUM
inner join
EMPLOYEE
on EMPLOYEE.SSN = DEPARTMENT.MGRSSN
where
PROJECT.PLOCATION = 'Stafford'
但是使用旧语法:
select
PROJECT.PNUMBER,
PROJECT.DNUM,
EMPLOYEE.LNAME,
EMPLOYEE.ADDRESS
-- and so on with the EMPLOYEE fields
from
PROJECT, DEPARTMENT, EMPLOYEE
where
PROJECT.PLOCATION = 'Stafford'
and DEPARTMENT.DNUMBER = PROJECT.DNUM -- This was the missing bit
and EMPLOYEE.SSN = DEPARTMENT.MGRSSN
答案 1 :(得分:2)
尝试这样的事情
select p.pnumber, d.dnumber,e.lname, e.[address], e.bdate
from department D
inner join project P on D.dnumber = P.dnum
inner join employee E on e.ssn = D.mgrssn
where p.location = 'STAFFORD'
答案 2 :(得分:2)
您的表连接不正确。你需要加入部门进行项目。
SELECT p.PNUMBER, p.DNUM, e.LNAME, e.ADDRESS, e.BDATE
FROM Project p
INNER JOIN Department d ON d.DNUMBER = p.DNUM
INNER JOIN Employee e ON e.ssn = d.MGRSSN
WHERE p.PLOCATION = 'STAFFORD';
也许您尚未了解其他联接类型。这应该也取决于你所拥有的:
SELECT PROJECT.PNUMBER, PROJECT.DNUM, EMPLOYEE.LNAME, EMPLOYEE.ADDRESS, EMPLOYEE.BDATE
FROM PROJECT, EMPLOYEE, DEPARTMENT
WHERE PLOCATION = 'STAFFORD'
AND DEPARMENT.DNUMBER = PROJECT.DNUM
AND DEPARTMENT.MGRSSN = EMPLOYEE.SSN;