INSERT INTO ... ON DUPLICATE KEY UPDATE递增语法

时间:2014-11-24 18:46:17

标签: mysql

我试图将一个值从一个表增加到另一个表,但我无法弄清楚正确的语法。有人可以帮我形成一个正确的陈述吗?提前谢谢你:

当前声明:

INSERT INTO points_1_day (nick, amount) 
(SELECT nick, SUM(amount) as increment 
FROM points_log 
WHERE dt >= NOW()-INTERVAL 1 day GROUP BY nick) 
ON DUPLICATE KEY UPDATE 
points_1_day.amount=points_1_day.amount+points_log.increment;

我收到此错误消息:

ERROR 1054 (42S22): Unknown column 'points_log.increment' in 'field list'

1 个答案:

答案 0 :(得分:3)

ON UPDATE子句中的表达式不能引用SELECT中的列。

但是他们可以引用VALUES(amount)来获取您尝试在给定行上插入的值。

INSERT INTO points_1_day (nick, amount) 
(SELECT nick, SUM(amount) as increment 
FROM points_log 
WHERE dt >= NOW()-INTERVAL 1 day GROUP BY nick) 
ON DUPLICATE KEY UPDATE 
points_1_day.amount=points_1_day.amount+VALUES(amount);

让我测试一下,看看它是否有效......

mysql> insert into points_1_day values (123, 10);
Query OK, 1 row affected (0.01 sec)

mysql> insert into points_log (nick, amount, dt) values (123, 15, NOW());
Query OK, 1 row affected (0.13 sec)

mysql> select * from points_1_day;
+------+--------+
| nick | amount |
+------+--------+
|  123 |     10 |
+------+--------+
1 row in set (0.00 sec)

mysql> INSERT INTO points_1_day (nick, amount)  (SELECT nick, SUM(amount) as increment  
    FROM points_log  WHERE dt >= NOW()-INTERVAL 1 day GROUP BY nick)  
    ON DUPLICATE KEY UPDATE  points_1_day.amount=points_1_day.amount+values(amount);
Query OK, 2 rows affected (0.02 sec)
Records: 1  Duplicates: 1  Warnings: 0

mysql> select * from points_1_day;
+------+--------+
| nick | amount |
+------+--------+
|  123 |     25 |
+------+--------+
1 row in set (0.00 sec)

mysql> INSERT INTO points_1_day (nick, amount)  (SELECT nick, SUM(amount) as increment  
    FROM points_log  WHERE dt >= NOW()-INTERVAL 1 day GROUP BY nick)  
    ON DUPLICATE KEY UPDATE  points_1_day.amount=points_1_day.amount+values(amount);
Query OK, 2 rows affected (0.00 sec)
Records: 1  Duplicates: 1  Warnings: 0

mysql> select * from points_1_day;
+------+--------+
| nick | amount |
+------+--------+
|  123 |     40 |
+------+--------+

是的,似乎有效。


说明:http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html说:

  

您可以在VALUES(col_name子句中使用UPDATE)函数   引用INSERT语句的INSERT ... ON DUPLICATE KEY UPDATE部分中的列值。换一种说法,   VALUES(col_name) in   ON DUPLICATE KEY UPDATE子句引用col_name的值   将插入,没有发生重复键冲突。这个   函数在多行插入中特别有用。 VALUES()   函数仅在INSERT ... UPDATE语句中有意义   否则返回NULL。例如:

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
  ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

这也适用于INSERT...SELECT。但VALUES()的参数是您要插入的列名,而不是SELECT中相应列的名称。