[英]Select max,min, last value from a column in mysql table
table format 表格式
id time_stamp
3 2013-09-05 12:00:00
5 2013-09-06 12:00:00
12 2013-09-07 12:00:00
2 2013-09-08 12:00:00
5 2013-09-09 12:00:00
8 2013-09-10 12:00:00
From the above table i want select min(id), max(id), last id, last time_stamp in single mysql select query statement 从上面的表中我想在单个mysql select查询语句中选择min(id),max(id),last id,last time_stamp
Needed output is: 需要的输出是:
min max last(val) last(time_stamp)
2 12 8 2013-09-09 12:00:00
i used following Query 我使用了以下查询
select id, min(id),max(id), time_stamp from table order by time_stamp limit 1
I am getting wrong latest id value 3 instead of 8 我得到错误的最新id值3而不是8
Check this if below SQL fiddle 如果低于SQL小提琴,请检查此项
http://www.sqlfiddle.com/#!2/e9cb1/2/0 http://www.sqlfiddle.com/#!2/e9cb1/2/0
Here is a method, using the substring_index()
/ group_concat()
trick: 这是一个方法,使用substring_index()
/ group_concat()
技巧:
select min(id), max(id),
substring_index(group_concat(id order by time_stamp desc), ',', 1) as lastid
from table ;
Assuming you mentioned the last(time_stamp) incorrectly in your question - Get the max, min as usual and then find out the last id and time stamp in a subquery which you can then JOIN to get all result in one row. 假设您在问题中错误地提到了最后一个(time_stamp) - 像往常一样获取max,min,然后找出子查询中的最后一个id和时间戳,然后可以JOIN将所有结果放在一行中。
MySQL 5.5.32 Schema Setup : MySQL 5.5.32架构设置 :
create table t (id int, time_stamp datetime);
insert into t values(3, '2013-09-05 12:00:00');
insert into t values(5, '2013-09-06 12:00:00');
insert into t values(12, '2013-09-07 12:00:00');
insert into t values(2, '2013-09-08 12:00:00');
insert into t values(5, '2013-09-09 12:00:00');
insert into t values(8, '2013-09-10 12:00:00');
Query 1 : 查询1 :
SELECT MIN(t.id), MAX(t.id), latest.id, latest.time_stamp
FROM t JOIN (
SELECT t.id, t.time_stamp
FROM t
ORDER BY time_stamp DESC
LIMIT 1) latest
| MIN(T.ID) | MAX(T.ID) | ID | TIME_STAMP |
|-----------|-----------|----|----------------------------------|
| 2 | 12 | 8 | September, 10 2013 12:00:00+0000 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.