七天之痒:一条SQL查询语句
有两个表,我要从每个表里按条件查出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
问题点数:20、回复次数:7Top
1 楼slayerbb(名字被抢了)回复于 2006-03-16 10:36:39 得分 4
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 descTop
2 楼dicklee1214(令狐冲)回复于 2006-03-16 10:42:04 得分 4
楼上的虽然不是效率最高的,但也是一个可行的方法,用exist替换in的写法可以更高效Top
3 楼dh20156(风之石)回复于 2006-03-16 10:43:43 得分 4
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 asc
Drop Table ta
Drop Table tb
/*
t_id t_txt
----------- ----------
1 btxt1
1 atxt1
2 atxt2
(所影响的行数为 3 行)
*/Top
4 楼dh20156(风之石)回复于 2006-03-16 10:44:32 得分 4
使用 UNION 组合两个查询的结果集的两个基本规则是:
所有查询中的列数和列的顺序必须相同。
数据类型必须兼容。
Top
5 楼job_2006(初学.net)回复于 2006-03-16 10:48:42 得分 4
select top 10 from(select top 10 from test1 a join test1 b on a.??=b.?? where ?? order by ?? desc ??)Top
6 楼xianggang101(tanjun)回复于 2006-03-16 10:52:22 得分 0
建立视图再查询三Top
7 楼fanweiwei(黑暗凝聚力量,堕落方能自由)回复于 2006-03-16 11:04:37 得分 0
上面的答案真确我测试过了Top




