如何在PostgreSQL中订购带有链接部分的行

时间:2017-09-14 16:42:46

标签: postgresql

我有一个 A 表格,其中包含以下列: ID,标题,条件

我还有另一张表 B ,其中包含有关表A中某些行的位置信息。表B包含 id,next_id,prev_id

如何根据表B中的信息对A中的行进行排序?

例如, 表A

UPDATE users
SET editoverride = 1
WHERE id IN
    (SELECT A.id
     FROM
       (SELECT users.id
        FROM users
        JOIN contractorscontractsappliedfor ON contractorscontractsappliedfor.contractorId = users.id
        JOIN usertenderstage ON usertenderstage.userId = users.id
        WHERE users.live = 1
          AND contractorscontractsappliedfor.contractid = 1
          AND usertenderstage.stageId = 2
          AND usertenderstage.statusid = 6) AS A)

表B

 id| title
 ---+-----
 1 | title1
 2 |  title2
 3 |  title3
 4 |  title4
 5 |  title5

我想得到这个结果:

 id| next_id | prev_id
 ---+-----
 2  | 1      | null
 5  | 4      | 3

应用此类后,我想按条件列进行排序。 我已经花了很多时间寻找解决方案,并希望得到你的帮助。

1 个答案:

答案 0 :(得分:0)

您必须为数据添加权重,以便您可以相应地进行排序。这个例子使用next_id,不确定你是否需要使用prev_id,你不能解释它的使用。

无论如何,这是一个代码示例:

-- Temporal Data for the test:
CREATE TEMP TABLE table_a(id integer,tittle text);
CREATE TEMP TABLE table_b(id integer,next_id integer, prev_id integer);
INSERT INTO table_a VALUES
(1,'title1'),
(2,'title2'),
(3,'title3'),
(4,'title4'),
(5,'title5');
INSERT INTO table_b VALUES
(2,1,null),
(5,4,3);

-- QUERY:
 SELECT
    id,tittle,
    CASE -- Adding weight
        WHEN next_id IS NULL THEN (id + 0.1)
        ELSE next_id
    END AS orden
FROM -- Joining tables
    (SELECT ta.*,tb.next_id
    FROM table_a ta
    LEFT JOIN table_b tb
    ON ta.id=tb.id)join_a_b
ORDER BY orden

结果如下:

id  |   tittle  |   orden
--------------------------
2   |   title2  |     1
1   |   title1  |   1.1
3   |   title3  |   3.1
5   |   title5  |     4
4   |   title4  |   4.1