2

我有一个包含许多行的表,如下所示:

+---------------------+------+
| utc                 | temp |
+---------------------+------+
| 2011-01-30 00:00:14 |   -3 |
| 2011-01-30 00:40:06 |   -4 |
| 2011-01-30 01:00:15 |   -4 |
| 2011-01-30 01:20:14 |   -4 |
| 2011-01-30 02:00:12 |   -4 |
| 2011-01-30 02:20:18 |   -4 |
| 2011-01-30 03:00:16 |   -4 |
|         ...         |  ... |

utc是 类型datetimetemp是 类型int

对于每一天,我想找到temp最接近当天中午的值。可能会生成一个如下所示的表:

+---------------------+------+
| utc                 | temp |
+---------------------+------+
| 2011-01-30 12:01:14 |   -3 |
| 2011-01-31 11:58:36 |   -4 |
| 2011-02-01 12:00:15 |   -5 |
| 2011-02-02 12:03:49 |   -7 |
| 2011-02-03 02:00:12 |   -8 |
|         ...         |  ... |

在一天之内找到这个很容易:

SELECT utc, temp FROM table WHERE DATE(utc)='2011-01-30' ORDER BY ABS(TIMESTAMPDIFF(SECOND,utc,DATE_ADD(DATE(utc),INTERVAL 12 HOUR))) LIMIT 1;

但不知何故,每天同时做这件事被证明更具挑战性。

(请注意,可能有比temp表中更多的值。)

4

1 回答 1

1

我会使用存储过程:

delimiter $$
create procedure get_temps(d0 date, d1 date)
begin
    declare d date;
    declare done tinyint default 0;
    declare cur_dates cursor for
        select distinct date(utc) as date 
        from `table`
        where date(utc) between d0 and d1;
    declare continue handler for not found
        set done = 1;
    -- Create a table to store the data
    create table if not exists tbl_temp_data (
        utc datetime,
        temp int
    );

    open cur_dates;
    temp_filter: while done=0 do
        fetch cur_dates into d;
        if done = 0 then
            insert into tbl_temp_data
            SELECT 
                utc, temp 
            FROM 
                `table` 
            WHERE 
                DATE(utc)=d
            ORDER BY 
                ABS(TIMESTAMPDIFF(SECOND,utc,DATE_ADD(DATE(utc),INTERVAL 12 HOUR))) 
            LIMIT 1;

        end if;
    end while;
end $$
delimiter ;
于 2013-09-03T16:23:55.367 回答