我编写了一个使用两列的查询,每一列都来自不同的表。我怎样才能为这些列建立索引,这可能吗?
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;
最佳答案
在SQL Server中,如果您想在不同表的列上创建索引,那么您可以创建Schema Bound View并在该 View 之上构建索引。
在您的情况下,创建一个架构绑定(bind) 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
现在您可以在此绑定(bind) View 上使用两列创建索引:
--Example index on the bound view.
CREATE UNIQUE CLUSTERED INDEX IDX_V1
ON MyBoundView (countryName, balance);
GO
您可能会找到this article有用。
关于SQL Server 对多个表列建立索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50538149/