SQL Server复制结果三遍

问题描述 投票:0回答:1

我正在尝试过滤我的结果,以输出在部门5控制的所有项目中工作的人员的姓名。我认为我在下面写的内容会给我想要的结果,但是它显示了工作人员的姓名在这些项目上各进行三次。我将采取什么措施对此进行补救?

SELECT e.Fname, e.Minit, e.Lname
FROM EMPLOYEE AS e, DEPARTMENT as d, PROJECT as p
WHERE p.Dnum=d.Dnumber AND d.Dnumber=e.Dno AND p.Dnum=5

输出结果:

John    B   Smith
John    B   Smith
John    B   Smith
Franklin    T   Wong
Franklin    T   Wong
Franklin    T   Wong
Joyce   A   English
Joyce   A   English
Joyce   A   English
Ramesh  K   Narayan
Ramesh  K   Narayan
Ramesh  K   Narayan
sql sql-server sql-server-2017
1个回答
0
投票
似乎您具有多对一关系,并且在执行ANSI-89(适用于1989年)联接时没有考虑到这一点。结果,由于表DEPARTMENTPROJECT中连接了多行,因此每个Employee会获得多行。

考虑到您仅在EMPLOYEE I中引用SELECT,我

假设

实际上需要EXISTSSELECT e.Fname, e.Minit, e.Lname FROM dbo.EMPLOYEE E WHERE E.Dno = 5 --Inferred as p.Dnum=5 and p.Dnum=d.Dnumber and d.Dnumber=e.Dno. Thus e.Dno = 5 AND EXISTS (SELECT 1 FROM dbo.DEPARTMENT D JOIN dbo.PROJECT P ON D.Dnumber = P.Dnum WHERE D.Dnumber = E.Dno);
但是,如果您不在乎员工是否有部门(或项目),则可以满足以下条件:

SELECT e.Fname, e.Minit, e.Lname FROM dbo.EMPLOYEE E WHERE E.Dno = 5;

© www.soinside.com 2019 - 2024. All rights reserved.