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
因为这两个指令都是从多个表中获取记录。
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
本文通过一个具体示例展示了如何将SQL语句中的UNION指令与ORDER BY联合使用来实现多表查询并合并结果集。示例中分别处理了不同条件下的数据,并按照指定字段进行排序。
1311

被折叠的 条评论
为什么被折叠?



