我正在使用mysql,如何在重复更新查询格式的插入中使用case / if else,
表t1,
VAL1 VAL2 TIME_STAMP
20.1 30.1 November, 07 2013 07:06:22+0000
22.1 33.1 November, 07 2013 07:07:22+0000
40.1 44.0 November, 07 2013 07:08:22+0000
表t1_last(t1的子表)
ID VAL1 MIN_VAL1 MAX_VAL1 VAL2 MIN_VAL2 MAX_VAL2 TIME_STAMP
1 22.1 20.1 22.1 33.1 30.1 33.1 November, 07 2013 07:07:22+0000
现在我要插入2013/11/07 07:08:22 time_stamp val1, val2与t1_last表min_val1,max_val1,min_val2,max_val2进行比较 分别需要将新值更新为val1,val2并更正 带有当前时间戳的最大值,最小值。
插入或更新查询,如:
id val1 min_val1 max_val1 val2 min_val2 max_val2 time_stamp
1 40.1 20.1 40.1 44.0 30.1 44.0 2013/11/07 07:08:22
Sqlfiddle link http://www.sqlfiddle.com/#!2/5be80/6
答案 0 :(得分:2)
使用重复密钥更新: -
INSERT INTO t1_last (id, val1, min_val1, max_val1, val2, min_val2, max_val2, time_stamp)
SELECT NULL, VAL1, VAL1, VAL1, VAL2, VAL2, VAL2, TIME_STAMP
FROM t1
INNER JOIN (SELECT MAX(TIME_STAMP) AS MaxTimeStamp FROM t1) Sub1
ON t1.TIME_STAMP = Sub1.MaxTimeStamp
ON DUPLICATE KEY UPDATE VAL1=VALUES(VAL1),
MIN_VAL1=IF(MIN_VAL1 > VALUES(VAL1), VALUES(VAL1), MIN_VAL1),
MAX_VAL1=IF(MAX_VAL1 < VALUES(VAL1), VALUES(VAL1), MAX_VAL1),
VAL2=VALUES(VAL2),
MIN_VAL2=IF(MIN_VAL2 > VALUES(VAL2), VALUES(VAL2), MIN_VAL2),
MAX_VAL2=IF(MAX_VAL2 < VALUES(VAL2), VALUES(VAL2), MAX_VAL2),
TIME_STAMP=VALUES(TIME_STAMP);