我有一个mySQl db(名称为"stock"),有50个表,每个表都有
id,符号,日期,时间,打开,高,低,关闭,列作为列(9列).
我想知道每张桌子的最后一张记录是什么,按日期和时间排序.
我是否必须对每个表的所有数据进行ORDER BY,或者有更好的方法来了解最后一条记录?
我正在请求帮助查询只返回db中每个表的最后一条记录.
谢谢
PS对于最后一个记录,我的意思是最近的日期然后是时间
有两种选择:
-- 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;
Run Code Online (Sandbox Code Playgroud)
不要忘记添加索引date.如果您可以同时添加大量记录,则必须添加:
ORDER BY id DESC -- In case that date is highest for records for last records
ORDER BY time DESC -- Every other case
Run Code Online (Sandbox Code Playgroud)
到查询结束
我将假设具有最大ID的记录是"最后一个"(假设严格增加的表中唯一的顺序ID).如果你有一个更好的"最后"定义可能会有所作为.
要获得一个"最后"记录,您可以:
Select * from table_1 where id = (select max(id) from table_1);
Run Code Online (Sandbox Code Playgroud)
要将所有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...
Run Code Online (Sandbox Code Playgroud)
特定于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...
Run Code Online (Sandbox Code Playgroud)
根据您的编辑(您实际定义"最后"的意思):
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...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32898 次 |
| 最近记录: |