如果查询包含constenation语法“ ||”,则sqlite停止使用索引。

发布于 2025-02-10 09:23:02 字数 709 浏览 1 评论 0原文

这是常规查询的查询计划。它使用索引应应有的:

sqlite> PRAGMA case_sensitive_like=on;
sqlite> explain query plan select * from users where login like 'username%' limit 10;
QUERY PLAN
`--SEARCH users USING INDEX login_index (login>? AND login<?)

这是相同查询的查询计划,但是使用Concatenation ||语法:

sqlite> PRAGMA case_sensitive_like=on;
sqlite> explain query plan select * from users where login like 'username' || '%' limit 10;
QUERY PLAN
`--SCAN users

相同的查询不使用索引并切换整个扫描整个表。

我要使用串联的原因||语法是因为否则用户名不会被识别为参数,即select * select * select * select *从登录的用户中select *?1 %'限制10不起作用 - sqlite认为查询具有0个参数。

This is a query plan for a regular LIKE query. It uses an index as it should:

sqlite> PRAGMA case_sensitive_like=on;
sqlite> explain query plan select * from users where login like 'username%' limit 10;
QUERY PLAN
`--SEARCH users USING INDEX login_index (login>? AND login<?)

This is a query plan for the same query, but that uses concatenation || syntax:

sqlite> PRAGMA case_sensitive_like=on;
sqlite> explain query plan select * from users where login like 'username' || '%' limit 10;
QUERY PLAN
`--SCAN users

The same query doesn't use an index and switches to scanning whole table.

The reason I want to use concatenation || syntax is because otherwise username won't be recognized as a parameter, i.e. select * from users where login like '?1%' limit 10 doesn't work - sqlite considers that query has 0 parameters.

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

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

发布评论

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

评论(1

可爱暴击 2025-02-17 09:23:02

那是正常的,有记录的行为。 喜欢 optimization 可以使用;他们之中:

类似或地球的右侧必须是字符串文字或绑定到字符串字面的参数,而不是以通配符开始。

您正在使用表达式。

您可以尝试的是将附加到您要绑定到准备和执行查询的代码中的参数的字符串末尾,而不是在SQL语句中:login of like?用户名%作为该参数。

That's normal, documented behavior. The LIKE optimization has a lot of rules and caveats about when it can be used; among them:

The right-hand side of the LIKE or GLOB must be either a string literal or a parameter bound to a string literal that does not begin with a wildcard character.

You're using an expression.

What you can try is appending the % to the end of the string you're binding to the parameter in the code that prepares and executes the query, not in the SQL statement: login LIKE ?, with username% as that parameter.

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