繁体   English   中英

从mysql表中的列中选择max,min,last值

[英]Select max,min, last value from a column in mysql table

表格式

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

从上面的表中我想在单个mysql select查询语句中选择min(id),max(id),last id,last time_stamp

需要的输出是:

min   max  last(val)  last(time_stamp)
2     12   8          2013-09-09 12:00:00

我使用了以下查询

select id, min(id),max(id), time_stamp from table order by time_stamp limit 1

我得到错误的最新id值3而不是8

如果低于SQL小提琴,请检查此项
http://www.sqlfiddle.com/#!2/e9cb1/2/0

这是一个方法,使用substring_index() / group_concat()技巧:

select min(id), max(id),
       substring_index(group_concat(id order by time_stamp desc), ',', 1) as lastid
from table ;

假设您在问题中错误地提到了最后一个(time_stamp) - 像往常一样获取max,min,然后找出子查询中的最后一个id和时间戳,然后可以JOIN将所有结果放在一行中。

SQL小提琴

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');

查询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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM