union all后结果集行顺序

[复制链接]
查看11 | 回复9 | 2009-10-15 18:59:57 | 显示全部楼层 |阅读模式
select a
from
(
select 1 a from dual
union all
select 2 a from dual
)
where rownum=1
请教下大家,类似上面的写法,能不能保证取到的行是union all的第一个select的行呢?
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
上面的可以,其他的就不一定了
union all默认按第1列结果的升序排列,所以你的1,2是1在前面的
最好在内联查询中显示order by,不要怕麻烦
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
好像没按第一列升序排列呀,跟版本有关?我的是817
SQL> select a
2from
3(
4select 3 a from dual
5union all
6select 2 a from dual
7)
8where rownum=1
9;

A
----------
3
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
看错了,union all是不排序的
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
本来是加了order by的,但是加了nulls last却不行,我是想没查到行时into null到变量里的
select
a
into v
from
(
select a

from

(

select 1 a

from dual

union all

select null

from dual

)

order by a nulls last
)
where rownum=1;
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
哦,谢谢啊,那不加order by 应该可以吧
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
这就不清楚导致保证不保证顺序了,其他的union ,intersect,minus都是按第1列升序的
你这个需求完全写第1个就搞定了,日常也是有规律地排序,union all是不是按从上到下union的顺序排的不是很清楚,不知道有没有文档支持
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
union all本身是不排序的,关于表里面的值是根据每个表的rowid来排序的,像这样写死的值就按照顺序来了
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
你是说
select *
from
(
select c1 from t
where c2='a'
union all
select c1 from t
where c2='b'
)
where rownum=1

select *
from
(
select c1 from t
where c2='b'
union all
select c1 from t
where c2='a'
)
where rownum=1返回的结果是一样的吗?
回复

使用道具 举报

千问 | 2009-10-15 18:59:57 | 显示全部楼层
原帖由 aszsj1984 于 2010-4-1 16:26 发表
本来是加了order by的,但是加了nulls last却不行,我是想没查到行时into null到变量里的
select
a
into v
from
(
select a

from

(

select 1 a

from dual

union all

select null

from dual

)

order by a nulls last
)
where rownum=1;

谁说NULLS LAST不行?我试了没问题。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行