SQL中的强制执行顺序

发布于 2025-01-23 19:10:16 字数 206 浏览 2 评论 0原文

我在某些条款中有一组条件,例如

WHERE id > 123456 
AND type LIKE 'type%'

问题,我希望查询首先运行整数比较,因为它显着减少了字符串比较需要运行的数据量。

但是,优化器选择首先运行字符串比较,从而迫使其运行非常缓慢。

有没有办法迫使我的Where子句的执行顺序?

I have a set of conditions in my where clause like

WHERE id > 123456 
AND type LIKE 'type%'

The issue is that I would like the query to run the integer comparison first, as it signficantly decreases the amount of data that the string comparison needs to run.

However, the optimizer chooses to run the string comparison first forcing it to run extremely slowly.

Is there a way to force the execution order of my where clause?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

口干舌燥 2025-01-30 19:10:16

我不知道强迫它以一定顺序运行,但是如果您使用CTE怎么办?

很刺耳,但也许可行?

WITH cte_yourdata AS
(
    SELECT  *
    FROM    yourTable
    WHERE   id > 123456 
)

SELECT  *
FROM    cte_yourdata
WHERE   type LIKE 'type%'

I don't know about forcing it to run in a certain order but what if you used a cte?

Pretty hacky but maybe workable?

WITH cte_yourdata AS
(
    SELECT  *
    FROM    yourTable
    WHERE   id > 123456 
)

SELECT  *
FROM    cte_yourdata
WHERE   type LIKE 'type%'
薄情伤 2025-01-30 19:10:16

SQL是声明性语言,因此通常不允许您指定条件执行顺序。但是,您有几种可能性:

  • ID上定义索引,而不是type
  • ID> ID类型和确保ID列比类型列更具选择性(缩小结果)。您尚未描述您的数据。
  • 在Oracle中,使用/*+ index(...)*/提示执行适当的索引
  • 使用实体CTE

,请指定您的DB供应商,并解释查询计划以获取更精确的答案。

SQL is declarative language hence it, in general, does not allow you to specify order of execution of conditions. You have several possibilities though:

  • define index on id and not on type
  • define index on both id and type and ensure id column is more selective (narrowing result) than type column. You haven't described your data.
  • in Oracle, use /*+ INDEX(...)*/ hint to enforce proper index
  • use materialized CTE

Please specify your db vendor and explain plan of your query for more precise answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文