2014-11-24 143 views
2

我試圖從一個表增加一個值到另一個表,但是我找不出正確的語法。有人可以幫助我形成正確的聲明嗎?預先感謝您:INSERT INTO ... ON DUPLICATE KEY UPDATE增量語法

當前聲明:

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' 
+0

它只是「增量」 - 雖然這可能不是唯一的問題!?! – Strawberry 2014-11-24 18:49:48

+0

@Strawberry如果我使用增量,我得到ERROR 1054(42S22):未知列'增量'在'字段列表'中。 – 2014-11-24 18:51:02

回答

3

的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中相應列的名稱。

+0

嗯,我同意的診斷 - 我對治癒 – Strawberry 2014-11-24 18:52:59

+0

@比爾卡爾文懷疑 - 這確實按預期工作!你能解釋你添加的VALUES語句嗎?我正在嘗試學習MySQL,我很好奇它爲什麼可以工作。 – 2014-11-24 18:56:36

相關問題