防止重复sql server

时间:2013-01-06 17:27:48

标签: sql-server join duplicates

好的,在这个查询中,我从5个表中提取信息,表公司,程序员,测试人员,经理和表合同。我将提取程序员,测试人员和管理人员的姓名和电话号码,以及他们所工作的公司,并且该公司负责管理该程序,因为x人的请求无关紧要。

问题在于下面的代码,某些信息会出现多次,因为有其他信息,比如程序员的姓名和电话号码会出现与公司的经理和测试人员一样多次。

我尝试使用左外连接,它会给我更多结果,所以如何解决这个问题,以便下次结果不会重复但是说NULL?

SELECT DISTINCT pg.name,
                pg.Tel_Nr,
                Mgr.name,
                Mgr.Tel_Nr,
                Ts.Name,
                Ts.Tel_Nr,
                Pg.Name,
                con.program_name
FROM Company AS Cm
INNER JOIN Programmer AS Pg ON Pg.company = Cm.name
INNER JOIN Manager AS Mg ON Mg.company = Cm.name
INNER JOIN Tester AS Ts ON Ts.company = Cm.name
INNER JOIN Contract AS Con ON Con.program_name = 'My Program'
AND Cm.name = Con.Company

1 个答案:

答案 0 :(得分:0)

当然,通过工作描述生成联系人详细信息列表会更有意义。像这样:

WITH Cte as (select Cm.name from 
      Contract as Con join Company as Cm on  Cm.name = Con.Company
     where Con.program_name = 'My Program')
SELECT pg.name,  pg.Tel_Nr, 'Programmer' as JobTitle
FROM  Cte   INNER JOIN
    Programmer as Pg  on Pg.company = Cte.name 
UNION ALL
SELECT Mgr.name,  Mgr.Tel_Nr,'Manager' as JobTitle
FROM  Cte   INNER JOIN
     Manager as Mg on Mg.company= Cte.name 
UNION ALL
SELECT Ts.Name,  Ts.Tel_Nr, 'Tester' as JobTitle
FROM  Cte   INNER JOIN
    Tester as Ts on Ts.company = Cte.name 

此解决方案部署公用表表达式(标记为Cte)以避免多次查询thr CompanyContract表。 Find out more