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

时间:2013-09-11 18:39:52

标签: mysql sql

表格式

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

从上表我想要选择min(id),max(id),last id,last time_stamp in single mysql select query statement

需要的输出是:

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

2 个答案:

答案 0 :(得分:6)

以下是一种使用substring_index() / group_concat()技巧的方法:

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

答案 1 :(得分:3)

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

SQL Fiddle

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

<强> Results

| MIN(T.ID) | MAX(T.ID) | ID |                       TIME_STAMP |
|-----------|-----------|----|----------------------------------|
|         2 |        12 |  8 | September, 10 2013 12:00:00+0000 |