日期:2014-05-17  浏览次数:20702 次

SQL SERVER 2005 ORDER BY和UNION的问题
有两个TABLE
TABLE_A (A列,日期A)
TABLE_B (B列,日期B)

我从两个TABLE各取出一条最新的数据

SELECT TOP 1 * FROM TABLE_A WHERE ORDER BY 日期A;
SELECT TOP 1 * FROM TABLE_B WHERE ORDER BY 日期B;

我想把两条数据用一个结果表示出来
SELECT TOP 1 * FROM TABLE_A WHERE ORDER BY 日期A
UNION
SELECT TOP 1 * FROM TABLE_B WHERE ORDER BY 日期B;

但是出现了错误,我想问题一下要怎样才能解决。

注:下面的这种方法不能用。
SELECT * FROM (SELECT TOP 1 * FROM TABLE_A WHERE ORDER BY 日期A) AS TR1
UNION
SELECT * FROM (SELECT TOP 1 * FROM TABLE_B WHERE ORDER BY 日期B) AS TR2;
请高手指点,谢谢了

------解决方案--------------------
要加上 all吧 

SQL code
SELECT * FROM (SELECT TOP 1 * FROM TABLE_A WHERE ORDER BY 日期A) AS TR1 
UNION all
SELECT * FROM (SELECT TOP 1 * FROM TABLE_B WHERE ORDER BY 日期B) AS TR2;

------解决方案--------------------
注:下面的这种方法不能用。
SQL code
SELECT * FROM (SELECT TOP 1 * FROM TABLE_A WHERE ORDER BY 日期A) AS TR1
UNION
SELECT * FROM (SELECT TOP 1 * FROM TABLE_B WHERE ORDER BY 日期B) AS TR2;

------解决方案--------------------
当然不能用了,ORDER BY 语句前面多了个"WHERE"
------解决方案--------------------
楼主在忽悠人?
------解决方案--------------------
SQL code
--TRY
SELECT TOP 1 * into #t1 FROM TABLE_A WHERE ORDER BY 日期A; 
SELECT TOP 1 * into #t2 FROM TABLE_B WHERE ORDER BY 日期B;
go
select * from #t1
union all
select * from #t2
drop table #t1
drop table #t2