的ON UPDATE子句中的表達式不能指從選擇列。
但它們可以引用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 ... ON DUPLICATE KEY UPDATE
語句的INSERT
部分列值。換句話說, 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
中相應列的名稱。
它只是「增量」 - 雖然這可能不是唯一的問題!?! – Strawberry 2014-11-24 18:49:48
@Strawberry如果我使用增量,我得到ERROR 1054(42S22):未知列'增量'在'字段列表'中。 – 2014-11-24 18:51:02