有两个表,我要从每个表里按条件查出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

解决方案 »

  1.   

    select top 10 * from (
    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
      

  2.   

    楼上的虽然不是效率最高的,但也是一个可行的方法,用exist替换in的写法可以更高效
      

  3.   

    TRY:
    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 行)
    */
      

  4.   

    使用 UNION 组合两个查询的结果集的两个基本规则是: 所有查询中的列数和列的顺序必须相同。
    数据类型必须兼容。 
      

  5.   

    select top 10 from(select top 10 from test1 a join test1 b on a.??=b.?? where ?? order by ?? desc ??)