多个表列上的SQL Server索引

时间:2018-05-26 00:00:20

标签: sql sql-server indexing

我编写了一个使用两列的查询,每列都来自不同的表。如何为这些列创建索引,甚至可能?

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;

2 个答案:

答案 0 :(得分:1)

这是您的查询:

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;

答案 1 :(得分:1)

SQL Server 中,如果要在不同表的列上创建索引,则可以创建Schema Bound View并在该视图之上构建索引。

在您的情况下,创建一个架构绑定视图:

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  

您可能会发现this article有用。