如果我把這個子查詢,其選擇支付任何項目銷售人員和他們的最高價,他們賣:SQL:提高加盟效率
:select *,
(select top 1 highestProductPrice
from orders o
where o.salespersonid = s.id
order by highestProductPrice desc) as highestProductPrice
from salespersons s
在這個
,以提高工作效率加盟
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
它仍然觸及每一個訂單記錄(它通過salespersonid似乎濾波前枚舉整個表。)但是你不能做到這一點:
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
連接中的where子句導致「多部分標識符」s.id「無法綁定。
有什麼方法可以通過連接將每個訂單組中的前1個連接起來,但沒有觸及訂單中的每條記錄?
你是什麼意思'觸及每個記錄'?它將不得不觸及每一條記錄**以找出哪一個需要成爲頂級1 **。如果你沒有按照你想要的順序存在*索引,那麼每次都必須在運行時執行(當然,它可能會緩存答案,或者構建一個可重用的臨時索引)。 –
當您將枚舉篩選爲僅可連接記錄時,查詢所花費的時間顯着減少。換句話說,只對我想要排名的記錄進行排名,而不排序基於salespersonid不會加入的記錄 –