簡體   English   中英

在SQL(Postgres)中合並所有命令

[英]union all in SQL (Postgres) mess the order

我有一個按日期排序的查詢,有一個查詢我已經簡化了一點,但基本上是:

select * from 
(select  start_date, to_char(end_date,'YYYY-mm-dd') as end_date from date_table
order by start_date ,end_date ) 
where start_date is null or end_date is null

它顯示了府令

但我補充

union all
select start_date, 'single missing day' as end_date  from 
calendar_dates
where db_date>'2017-12-12' and db_date<'2018-05-13'     

然后整個訂單搞砸了。 為什么會這樣呢? Union或union all應該僅將第一個查詢的數據集附加到第二個查詢,對不對? 它不應該在第一個查詢中弄亂順序,對嗎?

我知道這個查詢沒有任何意義,但是我已經簡化了它以顯示語法。

僅假設UNION ALL將按照您編寫查詢的順序追加查詢,就無法預測訂單的結果。

查詢計划器將按照其認為合適的順序執行查詢。 這就是為什么有ORDER BY子句的原因。 用它 !

例如,如果要強制第一個查詢的順序,然后第二個,請執行:

select * from 
(select  1, start_date, to_char(end_date,'YYYY-mm-dd') as end_date from date_table
order by start_date ,end_date ) 
where start_date is null or end_date is null
union all
select 2, start_date, 'single missing day' as end_date  from 
calendar_dates
where db_date>'2017-12-12' and db_date<'2018-05-13' 
ORDER BY 1

你誤會了。 該查詢:

select d.*
from (select start_date, to_char(end_date,'YYYY-mm-dd') as end_date
      from date_table
      order by start_date, end_date
     ) d
where start_date is null or end_date is null

不“顯示完美的秩序”。 我可能只是碰巧產生了所需的順序,但這是一個巧合。 以特定順序獲取結果的唯一方法是在最外面的SELECT使用ORDER BY 期。

因此,如果要按特定順序生成結果,則使用order by

select d.*
from ((select d.start_date, to_char(end_date, 'YYYY-mm-dd') as end_date, 1 as ord
       from date_table d
       where d.start_date is null or d.end_date is null
       order by start_date, end_date
      ) union all
      (select cd.start_date, 'single missing day' as end_date, 2 as ord
       from calendar_dates cd
       where cd.db_date > '2017-12-12' and cd.db_date < '2018-05-13' 
      )
     ) d
order by ord, start_date;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM