[英]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.