日期:2014-05-18  浏览次数:20488 次

刚遇到的一个select order by union问题:
select   top   1   *   from   Tb1   where   type=goods_type  
union   all
select   top   1   *   from   tb2   where   type=goods_type
union   all
select   top   1   *   from   tb3   where   type=goods_type
union   all
select   top   1   *   from   tb4   where   type=goods_type
执行正常

添加排序功能则出错语法错误
select   top   1   *   from   Tb1   where   type=类型1   order   by   enter_time   desc
union   all
select   top   1   *   from   tb2   where   type=类型2   order   by   enter_time   desc
union   all
select   top   1   *   from   tb3   where   type=类型3   order   by   enter_time   desc
union   all
select   top   1   *   from   tb4   where   type=类型4   order   by   enter_time   desc

改成
select   top   1   *   from   Tb1   where   type=类型1  
union   all
select   top   1   *   from   tb2   where   type=类型2  
union   all
select   top   1   *   from   tb3   where   type=类型3  
union   all
select   top   1   *   from   tb4   where   type=类型4  
order   by   enter_time   desc
结果不是我想要的那种,这种结果只是对整体记录排序,而我要的是先选出某一类型最新一个记录,然后把这些记录合并,请各位高手帮帮忙,如何解决


------解决方案--------------------
select top 1 * into #tt from TB1 where type=类型1 order by enter_time desc
select top 1 * into #tt from TB2 where type=类型2 order by enter_time desc
select top 1 * into #tt from TB3 where type=类型3 order by enter_time desc
select top 1 * into #tt from TB4 where type=类型4 order by enter_time desc

select * from #tt

试试

------解决方案--------------------
select top 1 * ,1 as px from Tb1 where type=类型1
union all
select top 1 * ,2 as px from tb2 where type=类型2
union all
select top 1 * ,3 as px from tb3 where type=类型3
union all
select top 1 * ,4 as px from tb4 where type=类型4
order by px,enter_time desc
------解决方案--------------------
错了,改下
select * from (
select top 1 Tb1.*,bh=1 from Tb1 where type=goods_type
union all
select top 1 tb2.*,2 from tb2 where type=goods_type
union all
select top 1 tb3.*,3 from tb3 where type=goods_type
union all
select top 1 tb4.*,4 from tb4 where type=goods_type)t
order by bh

------解决方案--------------------

select * from (select top 1 * from Tb1 where type=类型1 order by enter_time desc)a
union all
select * from (select top 1 * from tb2 where type=类型2 order by enter_time desc) b
union all
select * from (select top 1 * from tb3 where type=类型3 order by enter_time desc)c
union all
select * from (select top 1 * from tb4 where type=类型4 order by enter_time desc)d