【问题标题】:Using inner join instead of subquery使用内连接代替子查询
【发布时间】:2018-12-19 23:16:14
【问题描述】:

我使用子查询编写了一个查询,但我想知道是否有任何方法可以仅使用内部连接(或其他连接)来编写它,因为它更有效。

/*2.    List the name of the sales rep who serves the most customers*/

select Sr.REP_NUM, Fname, Lname, count(cust_num) As TotalCustomers from employee Em
inner join SALESREP Sr on Sr.REP_NUM = Em.EMP_Num
inner join Customer Cu on Cu.REP_NUM = Sr.REP_NUM
group by Sr.REP_NUM, fname, lname
having count(Cu.rep_num) = (select max(AllReps.MostReps) from
(select count(rep_num) As MostReps from Customer group by rep_num) As AllReps) 

提前致谢。

【问题讨论】:

    标签: sql sql-server inner-join


    【解决方案1】:

    您可以使用TOP (1)TOP (1) WITH TIES。这应该比HAVING 子句更有效:

    select top (1) with ties Sr.REP_NUM, em.Fname, em.Lname, count(*) As TotalCustomers
    from employee Em join
         SALESREP Sr
         on Sr.REP_NUM = Em.EMP_Num join
         Customer Cu
         on Cu.REP_NUM = Sr.REP_NUM
    group by Sr.REP_NUM, fname, lname
    order by count(*) desc;
    

    【讨论】:

    • 谢谢。为什么它应该比 HAVING 子句更好?效率?
    • 您是否在使用 SQL Server Management Studio (SSMS)?您可以轻松比较两个查询的执行计划并查看估计子树成本有何不同……以及实际运行两者并查看实际执行时间有何不同。显示预计执行计划 (Ctrl + L)。包括实际执行计划 (Ctrl + M)。
    • @fnklstn 使用此top(1) with ties 的数据传递次数少于您的子查询方法 - 我相信这就是声明。使用 having 子句本身并没有错,但这样做(这里)需要第二次遍历数据。但是,作为对这些节省的补偿,需要按要求排序。
    • 不是最佳解决方案,因为可能有超过 1 个销售代表具有相同数量的最大值
    • @fnklstn 。 . .如果您希望全部使用最大值,请使用TOP (1) WITH TIES。如果您只想要一个,请使用TOP (1)。我在答案中提到了这一点。
    【解决方案2】:

    最终使用了内连接:

    select * from
    (select Sr.REP_NUM, Fname, Lname, count(cust_num) As TotalCustomers from employee Em
    inner join SALESREP Sr on Sr.REP_NUM = Em.EMP_Num
    inner join Customer Cu on Cu.REP_NUM = Sr.REP_NUM
    group by Sr.REP_NUM, fname, lname) As AllCounts
    inner join
    (select max(AllCus.MostCusts) As Most from
    (select count(cust_num) As MostCusts from Customer group by rep_num) As AllCus) As MaxCusts
    on MaxCusts.Most = TotalCustomers
    

    【讨论】:

      猜你喜欢
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多