连接表时,从SQL Server返回重复数据

时间:2013-09-10 12:23:21

标签: sql sql-server

我有一张这样的表:

Email_tbl

plcid       Ecode
----------- -----------
23          001646
24          001646
25          E004
25          2274
25          2208
25          1868

我有另一张桌子Employee

Ecode   Ename
E004     jaseem
2274     jasir
2208      deepu
1868       rupa
001646     shafeer

我想获得Ename plcid=25,所以我在这里使用此查询:

SELECT em.Ename
FROM dbo.Email_tbl e
JOIN dbo.EmployeeMaster_tbl em ON em.Ecode IN (SELECT Ecode
                                               FROM Email_tbl
                                               WHERE plcid = 25)

但我的结果出了问题。我的查询出了什么问题?

3 个答案:

答案 0 :(得分:7)

SELECT  em.Ename
FROM    dbo.Email_tbl e
        JOIN dbo.EmployeeMaster_tbl em ON em.Ecode = e.ECode
WHERE e.plcid = 25 

答案 1 :(得分:2)

你为什么要加入桌子?为什么有3个答案'修复'不必要的连接?

SELECT em.Ename
FROM dbo.EmployeeMaster_tbl em
WHERE em.Ecode IN (SELECT Ecode
                   FROM Email_tbl
                   WHERE plcid = 25)

答案 2 :(得分:0)

    SELECT emp.Ename
    FROM Email_tbl e INNER JOIN Employee emp ON (e.Ecode = emp.Ecode)
    WHERE e.plcid = 25

这将导致多行,因为Employee中的多行具有Ecode for PLCID = 25