首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用inner join而不是join查询

使用inner join而不是join查询
EN

Stack Overflow用户
提问于 2018-12-20 07:16:15
回答 2查看 89关注 0票数 0

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

代码语言:javascript
复制
/*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) 

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-25 09:59:37

最终使用了内连接:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2018-12-20 07:18:43

您可以使用TOP (1)TOP (1) WITH TIES。这应该比HAVING子句工作得更好:

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53860483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档