我在MySQL中有一个表如下所示:
+------------+------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+------+-----+-------------------+-------+
| ts | timestamp | NO | | CURRENT_TIMESTAMP | |
| id_usuario | int(11) | YES | | NULL | |
| temp | float(3,1) | YES | | NULL | |
+------------+------------+------+-----+-------------------+-------+
让我们说这是存储在其中的数据:
+---------------------+------------+------+
| ts | id_usuario | temp |
+---------------------+------------+------+
| 2015-02-12 11:00:00 | 2 | 20.0 |
| 2015-02-15 10:00:00 | 2 | 21.0 |
| 2015-02-17 20:00:00 | 2 | 20.0 |
| 2015-02-18 11:00:00 | 1 | 23.5 |
| 2015-02-18 11:30:00 | 1 | 24.0 |
| 2015-02-19 12:00:00 | 1 | 23.5 |
| 2015-02-19 12:30:00 | 1 | 22.0 |
| 2015-02-19 15:00:00 | 1 | 23.5 |
| 2015-02-19 15:50:00 | 1 | 21.5 |
| 2015-02-20 14:00:00 | 2 | 27.0 |
| 2015-02-20 14:00:00 | 1 | 26.0 |
| 2015-02-20 21:54:33 | 2 | 22.0 |
+---------------------+------------+------+
现在......想象一下你前一天的旅行时间,并且想要获得表格中的最后一个输入。然后你前一天去旅行做同样的事情,等等过去7天......那就是它!然后想出了一张像这样的桌子:(注意:我没有及时出行!)
如果"选择now()"返回' 2015-02-20 13:00:00',此程序将返回:
+---------------------+------------+------+
| ts | id_usuario | temp | <-- day 12 is out of range
+---------------------+------------+------+ but was the last input before
| 2015-02-12 11:00:00 | 2 | 20.0 | day 14 at 13hs. So its ok!
| 2015-02-15 10:00:00 | 2 | 21.0 | <-- day 17,16,15 before 13hs
| 2015-02-18 11:30:00 | 1 | 24.0 | <-- day 18 before 13hs
| 2015-02-19 12:30:00 | 1 | 22.0 | <-- day 19 before 13hs
| 2015-02-19 15:50:00 | 1 | 21.5 | <-- day 20 before 13hs
+---------------------+------------+------+
所以问题是......我怎么能这样做?
答案 0 :(得分:0)
这就是我想要做的(更好的是,因为我也获得了每个id_usuario的信息),但我不确定代码效率。 注意:我在SQL世界中真的很新......这是大约一个星期不断研究互联网的结果!所以你可能会注意到一些硬编码......
CREATE FUNCTION somefun ()
RETURNS <SOMETHING>
BEGIN
DECLARE eot INT DEFAULT FALSE;
DECLARE ts_start TIMESTAMP DEFAULT NOW();
DECLARE ts_comp TIMESTAMP DEFAULT NOW();
DECLARE ts TIMESTAMP;
DECLARE usr_comp MEDIUMINT DEFAULT 0;
DECLARE usr MEDIUMINT;
DECLARE cur CURSOR FOR SELECT * FROM Temp_Usuario ORDER BY id_usuario, ts DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET eot = TRUE;
OPEN cur;
leer: REPEAT
FETCH cur INTO ts, usr, temp;
IF usr <> usr_comp THEN
SET usr_comp = usr;
SET ts_comp = ts_start;
END IF;
IF (ts < ts_comp) AND (ts_comp > DATE_SUB(ts_start, INTERVAL 6 DAY)) THEN
/* DO SOMETHING */
END IF;
UNTIL eot END REPEAT leer;
CLOSE cur;
RETURN ( <SOMETHING> );
END;
//
如果您看到一些方法可以使其更好或防止可能的错误,请告诉我......感谢大家!!