1

我在 Postgres 9.4 中有这个查询:

select id from question where id = any(
    array_cat(
        ARRAY[0,579489,579482,579453,561983,561990,562083]::integer[], 
        (select array(
            select id from question where id not in 
                (0,579489,579482,579453,561983,561990,562083)
            and status in (1, -1) 
            and created_at > 1426131436 order by id desc offset 0 limit 10 )
        )::integer[]
    )
)

它返回:

   id
--------
 561983
 561990
 562083
 579453
 579482
 579489
 580541
 580542
 580543
 580544
 580545
 580546
 580547
 580548
 580549
 580550
(16 rows)

但它的顺序不正确。我需要根据子数组的结果排序的结果:

array_cat(
        ARRAY[0,579489,579482,579453,561983,561990,562083]::integer[], 
        (select array(
            select id from question where id not in 
                (0,579489,579482,579453,561983,561990,562083)
            and status in (1, -1) 
            and created_at > 1426131436 order by id desc offset 0 limit 10 )
        )::integer[]
    )

我怎样才能做到这一点?

4

2 回答 2

3

基本:

由于您使用的是 Postgres 9.4,因此您可以使用新的WITH ORDINALITY

WITH t AS (
   SELECT *
   FROM   unnest('{0,579489,579482,579453,561983,561990,562083}'::int[])
                  WITH ORDINALITY AS t(id, rn)
   )
(
SELECT id
FROM   question
JOIN   t USING (id)
ORDER  BY t.rn
)
UNION ALL
(
SELECT id
FROM   question
LEFT   JOIN t USING (id)
WHERE  t.id IS NULL
AND    status IN (1, -1) 
AND    created_at > 1426131436
ORDER  BY id DESC
LIMIT  10
);

解释

  1. 由于您两次使用相同的数组,因此我在查询前添加了一个 CTE,您在其中提供了一次数组。unnest()它立即根据数组元素的顺序WITH ORDINALITY获取行号( )。rn

  2. 与其将子查询填充到数组中并将其转换回来,不如直接使用它。便宜得多。排序顺序是直接派生的id

  3. 而不是从给定的数组中排除 ID NOT IN(这对于 NULL 值可能很棘手)使用LEFT JOIN / IS NULL

  4. 只需将两个部分附加到UNION ALL. 括号需要ORDER BY在查询的每条腿上分开UNION ALL

  5. 决赛中的JOINto现在是多余的,我把它去掉了。questionSELECT

于 2015-04-11T05:03:09.380 回答
0
ORDER BY idx(your_array, your_element)

或者

ORDER BY your_array # your_element

数组内

select id from question where id = any(
    array_cat(
        ARRAY[0,579489,579482,579453,561983,561990,562083]::integer[], 
        (select array(
            select id from question where id not in 
                (0,579489,579482,579453,561983,561990,562083) and status in (1, -1) 
                and created_at > 1426131436 order by id desc offset 0 limit 10 )
        )::integer[]
    ) 
) ORDER BY array_cat(
    ARRAY[0,579489,579482,579453,561983,561990,562083]::integer[], 
    (select array(
        select id from question where id not in 
            (0,579489,579482,579453,561983,561990,562083) and status in (1, -1) 
            and created_at > 1426131436 order by id desc offset 0 limit 10 )
    )::integer[]
) # id
于 2015-04-11T04:56:41.843 回答