1

我正在使用 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 链接http://www.sqlfiddle.com/#!2/5be80/6

4

1 回答 1

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);
于 2013-11-08T11:48:09.290 回答