我想从我的以下查询中删除不必要的连接以提高效率。

时间:2015-06-01 12:01:42

标签: sql sql-server sql-server-2008 sql-server-2012

我有这个代码

select sales.customerid ,name1.FullName as CustomerName, sales.managerID ,  name2.FullName as ManagerName, sales.BranchID ,name3.FullName as BranchName, EmployeeID ,name4.FullName as EmployeeName

     from dbo.Sales as sales
    join dbo.name as name1 on name.id = sales.customerid
    join dbo.name as name2 on name.id = sales.managerid
    join dbo.name as name3 on name.id = sales.branchid
    join dbo.name as name4 on name.id = sales.employeeid

如何将连接数减少为1而不是使用同一个表进行多次连接?

2 个答案:

答案 0 :(得分:3)

除了你的别名,你查询没问题。如果它很慢,那么列需要编入索引。

如果您真的想摆脱联接,那么您唯一的选择就是改变架构。您可以包括主键,但添加与该ID对应的人员的姓名。

就个人而言,我坚持使用JOIN。如果发现自己一遍又一遍地写相同的连接,它可能是视图的好地方。

答案 1 :(得分:1)

目前您的当前查询没有任何问题,尽管您可能觉得它在美学上并不令人满意。 如果它运行缓慢,你可以尝试添加索引,或者这些是一些替代方案,但我并不是说它们更好:

使用交叉申请:

select s.customerid , cust.FullName as CustomerName, s.managerID, man.FullName as ManagerName,
s.BranchID, bran.FullName as BranchName, EmployeeID, empl.FullName as EmployeeName
    from dbo.Sales as s
    CROSS APPLY
    (Select n.FullName
    from dbo.name as n
    where n.id = s.customerid) cust
    CROSS APPLY
    (Select n.FullName
    from dbo.name as n
    where n.id = s.managerid) man
    CROSS APPLY
    (Select n.FullName
    from dbo.name as n
    where n.id = s.branchid) bran
    CROSS APPLY
    (Select n.FullName
    from dbo.name as n
    where n.id = s.employeeid) empl

SQL小提琴:http://sqlfiddle.com/#!6/bae69/1/0