我需要根据跨越多个表的条件从数据库中选择信息

时间:2013-11-10 17:19:41

标签: sql sql-server

Three of my database tables

Other three database tables

我有一个问题,我需要为位于斯塔福德的每个项目选择项目编号,控制部门编号,部门经理的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语句有什么问题吗? 抱歉,我无法弄清楚如何格式化

3 个答案:

答案 0 :(得分:4)

基本上,您错过了DEPARTMENTPROJECT上的加入。

我使用显式连接而不是过时的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;