Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL中的UNIONALL(Postgres)扰乱了秩序_Sql_Postgresql_Union_Union All - Fatal编程技术网

SQL中的UNIONALL(Postgres)扰乱了秩序

SQL中的UNIONALL(Postgres)扰乱了秩序,sql,postgresql,union,union-all,Sql,Postgresql,Union,Union All,我有一个查询是order by date,有一个查询我简化了一点,但基本上是: 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 sta

我有一个查询是order by date,有一个查询我简化了一点,但基本上是:

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应该只将第一个查询中的数据集附加到第二个查询中,对吗?它不应该在第一个查询中扰乱顺序,对吗

我知道这个查询毫无意义,但我已将其简化为
显示语法。

您弄错了。此查询:

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:


仅仅假设UNION ALL将按照您编写查询的顺序追加查询,您无法预测查询的结果

查询计划器将按其认为合适的顺序执行查询。这就是为什么你有ORDERBY条款。用它

例如,如果要强制执行第一个查询的顺序,则第二个查询,请执行以下操作:

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 * 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