union与order by 组合使用
UNION指令的目的是让两个SQL语句的结果集合并起来。这样看起来UNION似乎和JOIN很相似。
因为这两个指令都是从多个表中获取记录。
UNION的一个限制是这多个表的列记录要一致。不能一个取5列,一个取3列。
语法:
[SQL 语句 1]
UNION
[SQL 语句 2]
那么UNION和ORDER BY怎么联合使用?下面有一个例子:
select * from (select s.id si_id,s.short_name,m1.name,m2.code
from si s, rooms m1, cabinets m2, dev d
where 1 = 1
and d.room_id is not null
and d.cabinet_id is not null
and d.room_id = m1.id(+)
and d.cabinet_id = m2.id(+)
and s.id = d.siteid
order by s.short_name,m1.name,m2.code,d.sn
) s1
union
select * from (select s.id si_id,s.short_name,m1.name,m2.code
from si s, rooms m1, cabinets m2, dev d
where 1 = 1
and d.room_id is null
and d.cabinet_id is null
and d.room_id = m1.id(+)
and d.cabinet_id = m2.id(+)
and s.id = d.siteid(+)
order by s.short_name,m1.name,m2.code,d.sn
) s2
union
select * from (select s.id si_id,s.short_name,m1.name,m2.code
from si s, rooms m1, cabinets m2, dev d
where 1 = 1
and d.room_id is not null
and d.cabinet_id is null
and d.room_id = m1.id(+)
and d.cabinet_id = m2.id(+)
and s.id = d.siteid
order by s.short_name,m1.name,m2.code,d.sn
) s3