gpt4 book ai didi

sql-server - 对多列进行 JOIN 时使用索引

转载 作者:行者123 更新时间:2023-12-02 23:38:25 25 4
gpt4 key购买 nike

简单来说,我有两个表,contactsdonotcall

CREATE TABLE contacts
(
id int PRIMARY KEY,
phone1 varchar(20) NULL,
phone2 varchar(20) NULL,
phone3 varchar(20) NULL,
phone4 varchar(20) NULL
);
CREATE TABLE donotcall
(
list_id int NOT NULL,
phone varchar(20) NOT NULL
);
CREATE NONCLUSTERED INDEX IX_donotcall_list_phone ON donotcall
(
list_id ASC,
phone ASC
);

我想查看哪些联系人与特定 DoNotCall 电话列表中的电话号码匹配。为了更快地查找,我在 list_idphone 上索引了 donotcall

当我进行以下 JOIN 时,需要很长时间(例如 9 秒):

SELECT DISTINCT c.id
FROM contacts c
JOIN donotcall d
ON d.list_id = 1
AND d.phone IN (c.phone1, c.phone2, c.phone3, c.phone4)

Screenshot of execution plan

Execution plan on Pastebin

如果我分别在每个电话字段上离开加入,它的运行速度会快得多(例如 1.5 秒):

SELECT c.id
FROM contacts c
LEFT JOIN donotcall d1
ON d1.list_id = 1
AND d1.phone = c.phone1
LEFT JOIN donotcall d2
ON d2.list_id = 1
AND d2.phone = c.phone2
LEFT JOIN donotcall d3
ON d3.list_id = 1
AND d3.phone = c.phone3
LEFT JOIN donotcall d4
ON d4.list_id = 1
AND d4.phone = c.phone4
WHERE
d1.phone IS NOT NULL
OR d2.phone IS NOT NULL
OR d3.phone IS NOT NULL
OR d4.phone IS NOT NULL

Screenshot of execution plan

Execution plan on Pastebin

我的假设是第一个代码段运行缓慢,因为它没有利用 donotcall 上的索引。
那么,如何对多个列进行联接并仍然使用索引?

最佳答案

SQL Server 可能认为使用索引解析 IN (c.phone1, c.phone2, c.phone3, c.phone4) 成本太高。

您可以通过提示测试索引是否会更快:

SELECT c.*
FROM contacts c
JOIN donotcall d with (index(IX_donotcall_list_phone))
ON d.list_id = 1
AND d.phone IN (c.phone1, c.phone2, c.phone3, c.phone4)

从您发布的查询计划中,它显示第一个计划估计会生成 40k 行,但它只返回 21 行。第二个计划估计 1 行(当然也返回 21 行。)

你是statistics吗?最新?过时的统计信息可以解释查询分析器做出错误的选择。统计数据应该自动更新或每周更新一次。检查您的统计数据的年龄:

select  object_name(ind.object_id) as TableName
, ind.name as IndexName
, stats_date(ind.object_id, ind.index_id) as StatisticsDate
from sys.indexes ind
order by
stats_date(ind.object_id, ind.index_id) desc

您可以update them手动:

EXEC sp_updatestats;

关于sql-server - 对多列进行 JOIN 时使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18614026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com