给定一个简单的三表连接,当包含 ORDER BY 时,即使没有返回行,查询性能也会发生巨大变化。实际问题场景需要 30 秒才能返回零行,但在不包括 ORDER BY 时是即时的。为什么?
SELECT *
FROM tinytable t /* one narrow row */
JOIN smalltable s on t.id=s.tinyId /* one narrow row */
JOIN bigtable b on b.smallGuidId=s.GuidId /* a million narrow rows */
WHERE t.foreignId=3 /* doesn't match */
ORDER BY b.CreatedUtc /* try with and without this ORDER BY */
Run Code Online (Sandbox Code Playgroud)
我知道我可以在 bigtable.smallGuidId 上建立索引,但是,我相信在这种情况下这实际上会使情况变得更糟。
这是创建/填充表以进行测试的脚本。奇怪的是,smalltable 有一个 nvarchar(max) 字段似乎很重要。我使用 guid 加入 bigtable 似乎也很重要(我猜这使它想要使用哈希匹配)。
CREATE TABLE tinytable
(
id INT PRIMARY KEY IDENTITY(1, 1),
foreignId …
Run Code Online (Sandbox Code Playgroud)