3

我的三个数据库表

其他三个数据库表

我有一个问题,我需要为位于斯塔福德的每个项目选择项目编号、控制部门编号、部门经理的 Lname、地址和出生日期。我无法获得我想要的结果。

我试过了:

SELECT PROJECT.PNUMBER, PROJECT.DNUM, EMPLOYEE.LNAME, EMPLOYEE.ADDRESS, EMPLOYEE.BDATE
FROM PROJECT, EMPLOYEE, DEPARTMENT
WHERE PLOCATION = 'STAFFORD' AND DEPARTMENT.MGRSSN = EMPLOYEE.SSN;

得到:

+---------+------+---------+---------- ---+-----------+
| 编号 | DNUM | 名称 | 地址 | 日期 |
| 30 | 4 | 黄 | 683 沃斯,休斯敦,德克萨斯 | 55 年 12 月 8 日 |
| 10 | 4 | 黄 | 683 沃斯,休斯敦,德克萨斯 | 55 年 12 月 8 日 |
| 30 | 4 | 华莱士 | 291 BERRY, 贝莱尔, TX | 20-JUN-41 |
+---------+------+---------+---------- ---+-----------+

但我应该得到的是(或我想要的):

+---------+------+---------+---------- ---+-----------+
| 编号 | DNUM | 名称 | 地址 | 日期 |
| 10 | 4 | 华莱士 | 391 BERRY, 贝莱尔, TX | 20-JUN-41 |
| 30 | 4 | 华莱士 | 291 BERRY, 贝莱尔, TX | 20-JUN-41 |
+---------+------+---------+---------- ---+-----------+

谁能帮我弄清楚我的sql语句有什么问题?抱歉,我无法弄清楚如何格式化

4

3 回答 3

4

基本上,您错过了DEPARTMENTand上的连接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
于 2013-11-10T17:30:37.063 回答
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'
于 2013-11-10T17:30:29.313 回答
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;
于 2013-11-10T17:30:43.913 回答