Ordering by the order of values in a SQL IN() clause(按 SQL IN() 子句中的值顺序排序)
问题描述
我想知道是否存在(可能是更好的方法)按 IN() 子句中值的顺序进行排序.
问题是我有 2 个查询,一个获取所有 ID,第二个获取所有信息.第一个创建我希望第二个排序的 ID 的顺序.ID 以正确的顺序放在 IN() 子句中.
所以它会是这样的(非常简化):
SELECT id FROM table1 WHERE ... ORDER BY display_order, nameSELECT name, description, ... WHERE id IN ([id's from first])
问题在于第二个查询返回的结果与将 ID 放入 IN() 子句的顺序不同.
我找到的一个解决方案是将所有 ID 放入一个带有自动递增字段的临时表中,然后将其加入到第二个查询中.
还有更好的选择吗?
注意:由于第一个查询是由用户"运行的,而第二个查询是在后台进程中运行的,因此无法使用子查询将二合一查询组合在一起.p>
我正在使用 MySQL,但我认为让它注意其他数据库的选项可能会很有用.
使用 MySQL 的 FIELD()
函数:
SELECT 名称、描述、...从 ...WHERE id IN([ids, 任意顺序])ORDER BY FIELD(id, [ids in order])
FIELD()
将返回等于第一个参数(第一个参数本身除外)的第一个参数的索引.
FIELD('a', 'a', 'b', 'c')
将返回 1
FIELD('a', 'c', 'b', 'a')
将返回 3
如果您以相同的顺序将 id 粘贴到 IN()
子句和 FIELD()
函数中,这将完全符合您的要求.
I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause.
The problem is that I have 2 queries, one that gets all of the IDs and the second that retrieves all the information. The first creates the order of the IDs which I want the second to order by. The IDs are put in an IN() clause in the correct order.
So it'd be something like (extremely simplified):
SELECT id FROM table1 WHERE ... ORDER BY display_order, name
SELECT name, description, ... WHERE id IN ([id's from first])
The issue is that the second query does not return the results in the same order that the IDs are put into the IN() clause.
One solution I have found is to put all of the IDs into a temp table with an auto incrementing field which is then joined into the second query.
Is there a better option?
Note: As the first query is run "by the user" and the second is run in a background process, there is no way to combine the 2 into 1 query using sub queries.
I am using MySQL, but I'm thinking it might be useful to have it noted what options there are for other DBs as well.
Use MySQL's FIELD()
function:
SELECT name, description, ...
FROM ...
WHERE id IN([ids, any order])
ORDER BY FIELD(id, [ids in order])
FIELD()
will return the index of the first parameter that is equal to the first parameter (other than the first parameter itself).
FIELD('a', 'a', 'b', 'c')
will return 1
FIELD('a', 'c', 'b', 'a')
will return 3
This will do exactly what you want if you paste the ids into the IN()
clause and the FIELD()
function in the same order.
这篇关于按 SQL IN() 子句中的值顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按 SQL IN() 子句中的值顺序排序


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