简体   繁体   中英

SQL Server index on multiple table columns

I wrote a query which uses two columns and each of those columns come from different tables. How can I make an index for these columns and is it even possible?

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;

This is your 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;

From what I can tell, you want the highest balance in each country, along with duplicates, if any. You can get these using:

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);

To get these in order by country name, you need a subquery:

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;

In SQL Server , if you want to create an index on columns from different tables, then you can create a Schema Bound View and build your index on top of that view.

In you case, create a 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  

Now you can create an index with your two columns on this bound view:

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

You may find this article useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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