mySQL查询返回每个表的最后一条记录

时间:2012-02-02 15:34:05

标签: mysql sql

我有一个包含50个表的mySQl db(名称为“stocks”),每个表都带有

id,symbol,date,time,open,high,low,close,volume as columns(9列)。

我想知道每张桌子的最后一张记录是什么,按日期和时间排序。

我是否必须对每个表的所有数据进行排序,或者有更好的方法来了解最后一条记录?

我正在为一个只返回db中每个表的最后一条记录的查询提供帮助。

谢谢

PS对于最后一条记录,我的意思是最近的日期,然后是时间

3 个答案:

答案 0 :(得分:9)

有两种选择:

-- I would use this only if you need more than one records
SELECT * FROM table ORDER BY date DESC LIMIT 1;

-- Way to go:
SELECT * FROM table WHERE date = (SELECT MAX(date) FROM table) LIMIT 1;

不要忘记在date上添加索引。如果您可以同时添加许多记录,则必须添加:

ORDER BY id DESC -- In case that date is highest for records for last records
ORDER BY time DESC -- Every other case

到查询结尾

答案 1 :(得分:7)

我将假设具有最大ID的记录是“最后一个”(假设严格增加的表中唯一的顺序ID)。如果你有一个更好的“最后”定义可以产生影响。

要获得一个“最后”记录,您可以这样做:

Select * from table_1 where id = (select max(id) from table_1);

要将所有50个表的结果合并到一个结果集中,您可以执行以下操作:

Select * from table_1 where id = (select max(id) from table_1)
union
Select * from table_2 where id = (select max(id) from table_2)
union
Select * from table_3 where id = (select max(id) from table_3)
union...

特定于MySQL的解决方案可能是

Select * from table_1 order by id desc limit 1
union
Select * from table_2 order by id desc limit 1
union
Select * from table_3 order by id desc limit 1
union...

根据您的编辑(您实际定义“最后”的意思):

Select * from table_1 order by date desc, time desc, id desc limit 1
union
Select * from table_2 order by date desc, time desc, id desc limit 1
union
Select * from table_3 order by date desc, time desc, id desc limit 1
union...

答案 2 :(得分:0)

这是一种不对表进行排序的方法:

select * from tab1
 where time = (select max(time)
                 from tab1
                where date = (select max(date) from tab1))
   and date = (select max(date) from tab1)

它应该非常快,如O(c),只要两列都被索引,否则时间将只是O(n)