gpt4 book ai didi

sql - 如果 SQL 中存在语句超时

转载 作者:行者123 更新时间:2023-12-05 08:00:15 24 4
gpt4 key购买 nike

If exists 
(
select 1 from table A join table B
on A.id = B.id
)
BEgin
Select 'Pass'
END
Select 'Fail'

我对上面的查询感到困惑,它根本不执行,直到它被包装在 If exists 语句中时超时。

当声明

 select 1 from table A join table B
on A.id = B.id

已执行,需要 20 秒才能给出结果,但是当将其包装在 If exists 语句中时,它根本不会执行,最后在 4 -5 小时后我不得不取消它。这可能是什么原因?

最佳答案

你研究过执行计划吗?我怀疑性能问题比 exists 的最终使用更深入,如果完整的查询可用 - 或者至少是其结构的完整表示,它会有所帮助。在评论中,您指出了这种更精细的结构:

SELECT
1
FROM table_A AS a
LEFT JOIN ( -- << why a left join, is it achieving anything?
SELECT
* -- << not literally select * I hope
FROM table_B AS b
JOIN table_C AS c
ON b.thing = c.thing
WHERE B.ColumnA IN ( -- << avoid this type of IN()
SELECT -- >> if this result is big
columnX
FROM table_D AS d
)
) AS x
ON a.thing = x.thing
;

在外部查询中,您(或至少表明)仅执行“选择 1”,因此无需在嵌套子查询中选择无关字段。

您指出使用了左连接,但对细节知之甚少,我无法判断是否需要。

可能最明显需要改进的地方是使用 IN(此处为子查询)如果该子查询产生大量行,性能将会下降。为此,连接或使用 EXISTS 可能是更好的选择。

编辑:关于获得执行计划,考虑从最内层的嵌套开始独立运行每个子查询:

                                    SELECT      -- >> if this result is big
columnX
FROM table_D AS d

它是否使用索引,返回了多少行(也许只是为此做一个计数(*))

从那里开始到下一个子查询,并考虑备选方案。例如这可能有效:

            SELECT
thing -- << only that which is needed
FROM table_B AS b
JOIN table_C AS c
ON b.thing = c.thing
JOIN (
SELECT distinct -- >> not a fan of distinct but might help here
columnX
FROM table_D
) AS D
ON B.ColumnA = D.columnX

这 block 的执行计划告诉你什么?

这样处理应该有助于整体优化。

关于sql - 如果 SQL 中存在语句超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18590222/

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