如何在PostgreSQL中使用Order by子句并限制所有并集?

时间:2018-12-18 17:49:57

标签: database postgresql

我有一个查询,我想在同一表上用all all聚合多个子查询的结果,并且只返回有限数量的记录。

子查询1:

SELECT "bookings".* FROM "bookings"
WHERE "bookings"."guest_id" = 19317644 
    AND "bookings"."status" IN (0)
    AND (created_at > '2017-10-04 05:27:29.740508')
ORDER BY "bookings"."id" ASC LIMIT 1;

子查询2:

SELECT "bookings".* FROM "bookings"
WHERE "bookings"."guest_id" = 19317644 
    AND "bookings"."status" IN (1)
    AND (created_at > '2017-10-04 05:27:29.740508')
ORDER BY "bookings"."id" ASC LIMIT 1;

我想从两个查询的结果中总共显示一条记录。

2 个答案:

答案 0 :(得分:0)

您可以使用结果集中的列号对UNION的结果进行排序。因此,如果“ id”是“ select * from bookings”返回的第一列,则可以执行以下操作:

SELECT "bookings".* FROM "bookings"
WHERE "bookings"."guest_id" = 19317644 
    AND "bookings"."status" IN (0)
    AND (created_at > '2017-10-04 05:27:29.740508')

UNION ALL

SELECT "bookings".* FROM "bookings"
WHERE "bookings"."guest_id" = 19317644 
    AND "bookings"."status" IN (1)
    AND (created_at > '2017-10-04 05:27:29.740508')

ORDER BY 1

关于LIMIT,我不清楚您要做什么:仅显示每个查询中的一条记录,或显示两个查询结果中的一条记录。

最后,我不确定在生成示例时是否丢失了一些细节,但这可能更简单:

SELECT "bookings".* FROM "bookings"
WHERE "bookings"."guest_id" = 19317644 
    AND "bookings"."status" IN (0,1)
    AND (created_at > '2017-10-04 05:27:29.740508')

更新:

如果要显示一条记录总数,则只需在语句末尾添加LIMIT子句即可。例如:

create table foo (a int);
insert into foo (a) values (1);
create table bar (b int);
insert into bar (b) values (2);

select * from foo
union all
select * from bar
order by 1
limit 1

答案 1 :(得分:0)

使用CTE合并数据

    WITH client_1 AS (
    SELECT "bookings".* FROM "bookings"
    WHERE "bookings"."guest_id" = 19317644 
        AND "bookings"."status" IN (0)
        AND (created_at > '2017-10-04 05:27:29.740508')
    ORDER BY "bookings"."id" ASC LIMIT 1
    ), client_2 AS (
    SELECT "bookings".* FROM "bookings"
    WHERE "bookings"."guest_id" = 19317644 
        AND "bookings"."status" IN (1)
        AND (created_at > '2017-10-04 05:27:29.740508')
    ORDER BY "bookings"."id" ASC LIMIT 1
    ), consolidated AS (
SELECT * FROM client_1 UNION ALL SELECT * FROM CLIENT_2
)
SELECT * FROM CONSOLIDATED;

,然后排序,限制或在哪里  仅使用“合并”表,它将具有来自两个查询的数据