如何在mysql中的2个表中显示最后更新的记录

时间:2014-07-06 02:04:33

标签: mysql sql

我创建了2个表(businesstbl,businessupdatestbl)。现在,我想为每个已添加的业务显示最后的记录。该表应如下所示:

businesstbl

 bus_id   bus_name    
  1         bus1       
  2         bus2

businessupdatestbl

  bus_up_id   bus_up_description   bus_id(FK)   bus_up_date
   1            description1        1             2013-12-02
   2            description2        1             2013-01-02
   3            description3        2             2013-01-29  
   4            description4        2             2013-02-01
   5            description4        2             2013-01-01

结果应为:

  bus_id   bus_name   bus_up_description
   1        bus1       description1    
   2        bus2       description4

1 个答案:

答案 0 :(得分:1)

select b.*, bu.*
from businesstbl b
join businessupdatestbl bu on b.bus_id = bu.bus_id
join 
(
   select bus_id, max(bus_up_date) as max_bus_up_date
   from businessupdatestbl
   group by bus_id
) bumax on on bu.bus_id = bumax.bus_id and bu.bus_up_date = bumax.max_bus_up_date