在 SQLite WHERE 子句中组合大量条件

编程入门 行业动态 更新时间:2024-10-27 02:27:01
本文介绍了在 SQLite WHERE 子句中组合大量条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要检索与列表中存储的 ID 匹配的记录.在运行时生成的查询很简单:

I need to retrieve records that match IDs stored in a list. The query, generated at runtime, is simple:

SELECT [whatever FROM sometable] WHERE (id = 1) or (id = 5) or (id = 33).

相当于

SELECT [whatever FROM sometable] WHERE [id] IN (1, 5, 33);

这很好,但是如果列表包含数百或数千个 ID 呢?该语句将是巨大的,并且在某些时候 SQL 解析器可能会发出嘶嘶声,否则,性能可能会非常糟糕.如何以一种对检索的记录数量不那么敏感的方式执行此操作?

This is fine, but what if the list contains hundreds or thousands of IDs? The statement will be huge and at some point the SQL parser might croak, or if it does not, performance will probably be quite bad. How can I do this in a way that is not so sensitive to the number of records being retrieved?

(我不能只是遍历列表并一条一条检索记录的原因是我需要数据库为我做 ORDER BY.记录必须来自按特定字段排序的数据库,而该列表表示用户在网格中选择的记录,可以以多种方式进行排序.是的,我可以在检索记录后在代码中对记录进行排序,但这是 B 计划,因为我什至不需要持有它们都在一个数据结构中,只是为了正确排序.)

推荐答案

如果你真的有很多 ID 以至于你担心 SQL 解析器发出嘶嘶声,你可以将它们存储到一个临时表中,然后做一个交叉连接.

If you're really going to have so many IDs that you're worried about the SQL parser croaking, you can store them into a temporary table and do a cross-join.

简单地用一个(主键)列创建表,即 ID,然后用所需的 ID 填充它并使用类似的内容:

Simply create the table with one (primary key) column, the ID, then populate it with the desired IDs and use something like:

SELECT [whatever] FROM [sometable] st, [idtable] it WHERE st.id = it.id

该查询不会阻塞任何解析器,并且检索到的行将仅限于在临时表中具有 ID 的行.

That query won't choke any parser and the rows retrieved will be limited to those having the ID in the temporary table.

这不必成为临时表,当然,您可以将它放在一边,前提是您确保一次只有一个事物"使用它.

This doesn't have to be a temporary table, of course, you can leave it lying around provided you ensure only one "thing" uses it at a time.

更多推荐

在 SQLite WHERE 子句中组合大量条件

本文发布于:2023-10-25 14:31:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   句中   条件   SQLite

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!