非聚集索引可用于执行合并连接。唯一的前提是连接列与索引列顺序匹配。
试试这个。
DROP TABLE snapshot
CREATE TABLE snapshot (id int identity(1,1) primary key clustered ,batchid INT,sqltime DATETIME)
INSERT INTO snapshot(sqltime,batchid) VALUES('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1 ),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:20:54.077', 1),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:22:54.077', 2),
('2015-03-26 08:26:54.077', 3),
('2015-03-26 08:26:54.077', 3)
CREATE NONCLUSTERED INDEX IX_snapshot_Non_Clustered ON snapshot(batchid)include(sqltime)
SELECT * FROM snapshot s1 INNER MERGE JOIN snapshot s2 on S1.batchid = s2.batchid
在上述查询的执行计划中,您可以看到 Merge Join 在非聚集索引上,而不是在 id 上的聚集索引。