有两个表,我要从每个表里按条件查出Top 10 条,合并成一个结果,然后再从这合并后的20条中按条件再查出Top 10 条,我试过如下不行,一是union中不能包含两个order by,二是不能包含两个Top关键字,这个问题困扰好长时间了,还请高手解答:select top 10 tem.* from (
select top 10 * from tableA order by A_id desc
union all
select top 10 * from tableB order by B_id desc
) tem
order by A_id desc
select top 10 * from tableA order by A_id desc
union all
select top 10 * from tableB order by B_id desc
) tem
order by A_id desc
select * from tablea a where a.id
in
(
select top 10 id from tableb a order by a.id desc
)
union all
select * from tableb b where b.id
in
(
select top 10 id from tableb b order by b.id desc
)
) ttt
order by ttt.id desc
Create Table ta(a_id int identity(1,1),a_txt varchar(10))
Create Table tb(b_id int identity(1,1),b_txt varchar(10))Insert into ta Select 'atxt1' Union All
Select 'atxt2' Union All
Select 'atxt3'Insert into tb Select 'btxt1' Union All
Select 'btxt2' Union All
Select 'btxt3'Select Top 3 * From(
Select Top 10 a_id As 't_id',a_txt As 't_txt' From ta Order by ta.t_id desc
Union All
Select Top 10 b_id As 't_id',b_txt As 't_txt' From tb Order by tb.t_id desc
) t Order by t.t_id ascDrop Table ta
Drop Table tb/*
t_id t_txt
----------- ----------
1 btxt1
1 atxt1
2 atxt2(所影响的行数为 3 行)
*/
数据类型必须兼容。