[英]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. 在SQL Server中 ,如果要在来自不同表的列上创建索引,则可以创建“ 架构绑定”视图并在该视图之上构建索引。
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. 您可能会发现本文很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.