簡體   English   中英

多個表列上的SQL Server索引

[英]SQL Server index on multiple table columns

我編寫了一個查詢,該查詢使用兩列,每列均來自不同的表。 如何為這些列建立索引,甚至有可能?

select countryName, balance
from main.country c 
join main.person p on (c.countryId = p.countryId)
where balance = (select MAX(balance) 
                 from main.person p2 
                 join main.country c2 on (c2.countryId = p2.countryId)
                 where c.countryId = c2.countryId 
                   and p.countryId = p2.countryId)
order by countryName;

這是您的查詢:

select countryName, balance
from main.country c join
     main.person p
     on c.countryId = p.countryId
where balance = (select MAX(balance)
                 from main.person p2 join
                      main.country c2
                      on c2.countryId = p2.countryId
                 where c.countryId = c2.countryId and p.countryId = p2.countryId
                )
order by countryName;

據我所知,您希望每個國家/地區擁有最高的余額以及重復項(如果有)。 您可以使用以下方法獲取它們:

select top (1) with ties c.countryName, p.balance
from main.country c join
     main.person p
     on c.countryId = p.countryId
order by rank() over (partition by c.countryId order by p.balance desc);

要按國家/地區名稱排序,您需要一個子查詢:

select cp.*
from (select top (1) with ties c.countryName, p.balance
      from main.country c join
           main.person p
           on c.countryId = p.countryId
      order by rank() over (partition by c.countryId order by p.balance desc)
     ) cp
order by countryName;

SQL Server中 ,如果要在來自不同表的列上創建索引,則可以創建“ 架構綁定”視圖並在該視圖之上構建索引。

在這種情況下,請創建架構綁定視圖:

CREATE VIEW MyBoundView
WITH SCHEMABINDING  
AS  
   -- YOU QUERY 
   select countryName, balance
   from main.country c join main.person p on(c.countryId=p.countryId)
   where balance=(select MAX(balance) from main.person p2 join main.country c2 
   on(c2.countryId=p2.countryId)
   where c.countryId=c2.countryId and p.countryId=p2.countryId)
   order by countryName;  

GO  

現在,您可以在此綁定視圖上使用兩列創建索引:

--Example index on the bound view.  
CREATE UNIQUE CLUSTERED INDEX IDX_V1   
   ON MyBoundView (countryName, balance);  
GO  

您可能會發現本文很有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM