简体   繁体   English

SQL:提高连接效率

[英]SQL: improving join efficiency

If I turn this sub-query which selects sales persons and their highest price paid for any item they sell:如果我打开这个子查询,它选择销售人员及其为他们出售的任何商品支付的最高价格:

select *,
    (select top 1 highestProductPrice
     from   orders o
     where  o.salespersonid = s.id
     order by highestProductPrice desc ) as highestProductPrice
from salespersons s

in to this join in order to improve efficiency:为了提高效率,加入到这个join中:

select *, highestProductPrice
from   salespersons s join (
       select salespersonid, highestProductPrice, row_number(
           partition by salespersonid 
           order by salespersonid, highestProductPrice) as rank
       from orders ) o on s.id = o.salespersonid

It still touches every order record (it enumerates the entire table before filtering by salespersonid it seems.) However you cannot do this:它仍然涉及每个订单记录(它似乎在按销售人员过滤之前枚举了整个表。)但是你不能这样做:

select *, highestProductPrice
from   salespersons s join (
       select salespersonid, highestProductPrice, row_number(
           partition by salespersonid 
           order by salespersonid, highestProductPrice) as rank
       from orders 
       where orders.salepersonid = s.id) o on s.id = o.salespersonid

The where clause in the join causes a `multi-part identifier "s.id" could not be bound.连接中的 where 子句导致无法绑定“多部分标识符”“s.id”。

Is there any way to join the top 1 out of each order group with a join but without touching each record in orders?有什么方法可以加入每个订单组中的前 1 个加入但不触及订单中的每条记录?

Try尝试

SELECT
  S.*, 
  T.HighestProductPrice
FROM   
  SalesPersons S

  CROSS APPLY 
  (
    SELECT TOP 1 O.HighestProductPrice
    FROM Orders O
    WHERE O.SalesPersonid = S.Id
    ORDER BY O.SalesPersonid, O.HighestProductPrice DESC
  ) T 

would

select s.*, max(highestProductPrice)
   from salespersons s 
   join orders o on o.salespersonid = s.id
group by s.*

or或者

select s.*, highestProductPrice
   from salespersons s join (select salepersonid, 
                             max(highestProductPrice) as highestProductPrice
                             from orders o) as o on o.salespersonid = s.id

work?工作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM