Order by field with SQLite(使用 SQLite 按字段排序)
问题描述
我实际上正在从事一个 Symfony 项目,我们正在使用 Lucene 作为我们的搜索引擎.我试图使用 SQLite 内存数据库进行单元测试(我们使用的是 MySQL),但我偶然发现了一些东西.
I'm actually working on a Symfony project at work and we are using Lucene for our search engine. I was trying to use SQLite in-memory database for unit tests (we are using MySQL) but I stumbled upon something.
项目的搜索引擎部分使用 Lucene 索引.基本上,您查询它并获得一个有序的 id 列表,您可以使用 Where In() 子句查询您的数据库.问题是查询中有一个 ORDER BY Field(id, ...) 子句,它按照与 Lucene 返回的结果相同的顺序对结果进行排序.
The search engine part of the project use Lucene indexing. Basically, you query it and you get an ordered list of ids, which you can use to query your database with a Where In() clause. The problem is that there is an ORDER BY Field(id, ...) clause in the query, which order the result in the same order as the results returned by Lucene.
有没有使用 SQLite 的 ORDER BY Field 的替代方法?还是有另一种方法可以像 Lucene 一样对结果进行排序?
Is there any alternative to ORDER BY Field using SQLite ? Or is there another way to order the results the same way Lucene does ?
谢谢:)
简化的查询可能如下所示:
Simplified query might looks like this :
SELECT i.* FROM item i
WHERE i.id IN(1, 2, 3, 4, 5)
ORDER BY FIELD(i.id, 5, 1, 3, 2, 4)
推荐答案
这是相当讨厌和笨拙,但它应该工作.创建一个临时表,并插入 Lucene 返回的有序 ID 列表.将包含项目的表加入到包含有序 ID 列表的表中:
This is quite nasty and clunky, but it should work. Create a temporary table, and insert the ordered list of IDs, as returned by Lucene. Join the table containing the items to the table containing the list of ordered IDs:
CREATE TABLE item (
id INTEGER PRIMARY KEY ASC,
thing TEXT);
INSERT INTO item (thing) VALUES ("thing 1");
INSERT INTO item (thing) VALUES ("thing 2");
INSERT INTO item (thing) VALUES ("thing 3");
CREATE TEMP TABLE ordered (
id INTEGER PRIMARY KEY ASC,
item_id INTEGER);
INSERT INTO ordered (item_id) VALUES (2);
INSERT INTO ordered (item_id) VALUES (3);
INSERT INTO ordered (item_id) VALUES (1);
SELECT item.thing
FROM item
JOIN ordered
ON ordered.item_id = item.id
ORDER BY ordered.id;
输出:
thing 2
thing 3
thing 1
是的,这种 SQL 会让人不寒而栗,但我不知道 ORDER BY FIELD
的 SQLite 等价物.
Yes, it's the sort of SQL that will make people shudder, but I don't know of a SQLite equivalent for ORDER BY FIELD
.
这篇关于使用 SQLite 按字段排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 SQLite 按字段排序


- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01