从两个表中获取最新日期

时间:2014-06-26 06:52:30

标签: php mysql sql sql-server database

我有两张桌子

表1:

    ______ID_______|_______serials______|____Date_____|__include__
          20       |         1123       |   22-05-2014|    yes
          20       |         2231       |   12-06-2013|    No
          21       |         3213       |   24-01-2014|    yes
          22       |         5123       |   27-10-2012|    yes
          20       |         1213       |   02-03-2014|    yes 

表2:

   ______ID_______|______serials_______|____Date_____|__Rma__
          1       |         1123       |   01-05-2014|   1
          2       |         2231       |   22-06-2014|   7
          3       |         3353       |   20-01-2013|   5
          4       |         1213       |   27-03-2014|   2
          5       |         5123       |   06-03-2014|   9

我需要来自两个表的匹配序列的数据,需要从两个表中提取最近的日期。 这就是我期待输出的方式

_____ID_______|_______serials______|__RecentDate_|__include__|__ID__|__serial__|__Rma__
     20       |         1123       |   22-05-2014|    yes    |  1   |  1123    |   1
     20       |         2231       |   22-06-2014|    No     |  2   |  2231    |   7
     20       |         1213       |   27-03-2014|    yes    |  4   |  1213    |   2
     22       |         5123       |   06-03-2014|    yes    |  5   |  5123    |   9

任何人都可以帮助我。

3 个答案:

答案 0 :(得分:2)

SELECT  t1.id, t1.serials,
        CASE WHEN t1.date > t2.date THEN t1.date ELSE t2.date END recentDate,
        t1.include, t2.id, t2.serials, t2.rma
FROM    table1 t1
JOIN    table2 t2
ON      t2.serials = t1.serials

答案 1 :(得分:0)

简单连接或内连接的基本sql。

select * 
from table_1 a, table_2 b
where a.serials = b.serials;

使用order by

进行最近的尝试
select * 
from table_1 a, table_2 b
where a.serials = b.serials
order by a.date;

答案 2 :(得分:0)

Select t.id,serials,s.Date,include,t1.id,t1.serials
from table1 t
join table2 t1
on t.serials = t1.serials
join(

Select Serials,max(Date) 'date'
from (
        Select Serials ,DATE
        from table1 
        union all 
        Select Serials ,DATE
        from table2 

        )
group by serials        
) s on t.serials = s.serials