使用 OR 或 IN 子句查询有序列表

lum*_*umo 2 query order-by

我正在items从数据库中查询并将其显示给用户。(在我的示例中,我将contacts在 table 中使用tContacts

用户items按他决定的顺序选择几个(用户可以随机选择项目,因此不能指定要订购的列)。

在应用程序中,我itemsordered list.

目前我查询这些对象的更多详细信息one-by-one

是否可以创建一个带有“有序列表”的查询,它items相同的顺序返回?

类似于(是的,这很丑 - 可能也达到了最大 sql 查询大小):

SELECT * FROM (
    --how to append this list...
    SELECT 0 as listIndex, * from tContacts where conIdContact = 13259;
    SELECT 1 as listIndex, * from tContacts where conIdContact = 12472;
    [...]
    SELECT 568 as listIndex, * from tContacts where conIdContact = 12422;
)
ORDER BY listIndex
Run Code Online (Sandbox Code Playgroud)
  • 或:我是否必须继续查询 one-by-one
  • 或:这是否需要临时表(插入 id 和优先级),然后查询,然后再次删除临时表。
  • 或:查询 abatch并重新排序应用程序代码中的项目(由于列表可能很大,这可能会很慢)

注意:首选独立于数据库的解决方案(mariadb / mysql、postgresql 和 h2 被认为用于生产。

我的临时表概念:

CREATE TEMPORARY TABLE temp_OrderedContacts(
    listIndex INT NOT NULL DEFAULT 0,
    contactId INT NOT NULL DEFAULT 0
);

INSERT INTO temp_OrderedContacts (listIndex, contactId)
VALUES (0,13259), (1,12472), (2,12422);

SELECT * FROM tContacts
JOIN temp_OrderedContacts ON (tContacts.conIdContact = temp_OrderedContacts.contactId)

DROP TABLE temp_OrderedContacts;
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

Postgres 解决方案是将所有 ID 放入一个数组中,然后使用如下内容:

select t.*, il.listindex
from contacts t
   join unnest(array[13259, 12472, ..., 12422]) with ordinality as il(id, listindex) 
     on t.conidcontact = il.id
order by il.listindex;
Run Code Online (Sandbox Code Playgroud)

(以上实际上是标准的 ANSI SQL - 但据我所知,只有 Postgres 和 HSQLDB 支持)

该数组也可以在准备好的语句中作为参数传递(或您正在使用的编程语言中的任何术语)。


如果您可以构建动态查询,另一种选择是使用行值构造函数:

select t.*, il.listindex
from contacts t
   join ( 
      values 
        (1, 13259), 
        (2, 12472),  
        ..... 
        (568, 12422)
  ) as il(listindex, id) on t.conidcontact = il.id
order by il.listindex;
Run Code Online (Sandbox Code Playgroud)

(以上为100%标准ANSI SQL)