SQL Server 对多个表列建立索引

标签 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;

最佳答案

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/

相关文章:

SQL - 每列的条件

python - 不仅查找字符串中子字符串的第一个索引 - python 2.7

sql-server - 修改 MS SQL 2008 R2 中所有表中主键的填充因子

sql-server - 在 SSDT 模式比较中,如何忽略 "Schema"类型对象的差异

sql-server - 如何在sql中计算客户的天数金额

mysql - 为什么 EXPLAIN 的输出在每个 SHOW 索引后都会改变?

sql - Oracle SQL 在具有相同日期的多行之间进行选择

mysql - 如何处理多个连接

SQL查询在内部联接期间连接两列

c# - SQL Server : How to copy a file (pdf, doc, txt...) 存储在 CLR 存储过程中的文件的 varbinary(max) 字段中?