MySQL在15分钟内排第一

时间:2014-03-28 08:48:45

标签: mysql sql database

我希望在15分钟内完成第一次记录。

我有一个MySQL表,其日期时间行的间隔约为1分钟,我想要检索第一个记录,然后再检索下一个15分钟内的第一个记录。我很困惑是否使用join或MySQL变量或嵌套查询。即使你不知道正确的指导我应该使用变量或加入或嵌套?

具体来说,我们有一个表,其中一列date_timestamp为

+---------------------+
|   date_timestamp    |
+---------------------+
| 2014-01-07 11:49:42 |
| 2014-01-07 11:50:12 |
| 2014-01-07 11:50:31 |
| 2014-01-07 11:50:42 |
| 2014-01-07 11:51:22 |
| 2014-01-07 11:51:42 |
| 2014-01-07 11:52:52 |
| 2014-01-07 11:53:12 |
| 2014-01-07 11:53:32 |
| 2014-01-07 11:54:22 |
| 2014-01-07 11:55:42 |
| 2014-01-07 11:58:02 |
| 2014-01-07 11:59:22 |
| 2014-01-07 12:00:02 |
| 2014-01-07 12:00:42 |
| 2014-01-07 12:01:32 |
| 2014-01-07 12:01:52 |
| 2014-01-07 12:02:22 |
| 2014-01-07 12:03:42 |
| 2014-01-07 12:04:42 |
| 2014-01-07 12:05:02 |
+---------------------+

i want the output to be if i select 5 minute interval 
+---------------------+
|   date_timestamp    |
+---------------------+
| 2014-01-07 11:49:42 |
| 2014-01-07 11:54:22 |
| 2014-01-07 11:59:22 |
| 2014-01-07 12:04:42 |
+---------------------+

2 个答案:

答案 0 :(得分:1)

更新(调整为满足您的样本数据并忽略秒数):

select date_timestamp from (
select 
date_timestamp
, if(date_format(date_timestamp, '%Y-%m-%d %H:%i:00') = @a, 1, 0) as equals
, if(date_format(date_timestamp, '%Y-%m-%d %H:%i:00') = @a, @a:=@a + interval 5 minute, @a) as mya
from my_table, 
(select @a := (select date_format(min(date_timestamp), '%Y-%m-%d %H:%i:00') from my_table)) var_init 
order by date_timestamp
) sq
where equals = 1;

原始回答:

我会使用用户定义的变量。

测试数据:

create table interv(id int auto_increment primary key, myd datetime);

insert into interv(myd) values 
(now()), 
(now() + interval 7 minute), 
(now() + interval 9 minute), 
(now() + interval 15 minute), 
(now() + interval 16 minute),
(now() + interval 30 minute), 
(now() + interval 35 minute);

查询:

select id, myd from (
select 
id
, myd
, if(myd = @a, 1, 0) as equals
, if(myd = @a, @a:=@a + interval 15 minute, @a) as mya
from interv, 
(select @a := (select min(myd) from interv)) var_init 
order by myd
) sq
where equals = 1;

结果:

| ID |                          MYD |
|----|------------------------------|
|  1 | March, 28 2014 09:03:23+0000 |
|  4 | March, 28 2014 09:18:23+0000 |
|  6 | March, 28 2014 09:33:23+0000 |

答案 1 :(得分:0)

问题不清楚, 如果你正在使用mYSQL,那么去获取最后一个被插入的行

SELECT * 
FROM tablename
ORDER BY id DESC
LIMIT 1

$sql = "SELECT * FROM table WHERE id = LAST_INSERT_ID()";