2012-01-14 84 views
0

如何使用SQL从两个表中选择最新的记录?如何从两个表中选择最新的记录SQL?

"select * from Table1,Table2 WHERE Date=(SELECT MAX(Date) FROM Table1,Table2)" 

----------- ------------- 
| table1 | | table2 | 
----------- ------------- 
----------- ------------- 
| title | | title  | 
----------- ------------- 
| text | | text  | 
----------- ------------- 
| date | | date  | 
----------- ------------- 
+1

什么是从预期的输出?来自表1或2的记录中的最后一条记录(最后来自表1,最后来自表2),或者甚至有1条记录,其中有2个标题,2个文本和2个日期? – Eddy 2012-01-14 19:34:35

回答

6

这将做到这一点:

SELECT TOP 1 * FROM 
(
    SELECT * FROM Table_1 
    UNION ALL 
    SELECT * FROM Table_2 
) 
AS ALL_RECORDS 
ORDER BY Date DESC 
+0

虽然,你真的应该避免*,而是选择你需要的列。 。 。 – XIVSolutions 2012-01-14 19:40:18

3

试着这么做:

with tmp(title, text, date) as 
(
select title, text, date from table1 
union 
select title, text, date from table2 
) 
select top 1 * from tmp 
order by date desc 

这应该解决您的问题。

+1

安德烈亚斯罗德打败了我。 +1 – XIVSolutions 2012-01-14 19:40:47

1

SELECT * FTOM Table1,Tble2 ...创建一个交叉连接(两组记录的笛卡尔乘积),所以它将成为具有相同日期的多条记录。您必须指定更多条件才能获取一条记录,并且可能使用一些连接。 如果你想从两个表中选择一条记录,例如Table1的记录比Table2更新,我认为使用联合是个好主意。

SELECT col1, col2, col3, col4, ..., coln max(Date) FROM (
    SELECT * FROM Table1 UNION 
    SELECT * FROM Table2 
) GROUP BY col1, col2, col3, col4, ..., coln 
ORDER BY Date; 
相关问题