具有ORDER BY和LIMIT的Postgres UNION

时间:2019-10-31 10:15:20

标签: postgresql

是否可以这样做:

SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push = 1
UNION ALL
SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push IS NULL ORDER BY random() LIMIT 50

由于第二个查询上的ORDER BY和LIMIT而失败。反正有这样做吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以将第二个查询放入子查询中:

SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push = 1

UNION ALL

SELECT 
    * 
FROM (
    SELECT * FROM public."LamcApiCalls" WHERE generalstatuscode=0 AND sendondate < NOW() AND push IS NULL ORDER BY random() LIMIT 50
) s