Skip to content

Instantly share code, notes, and snippets.

@hatappo
Created August 12, 2013 06:16
Show Gist options
  • Save hatappo/6208599 to your computer and use it in GitHub Desktop.
Save hatappo/6208599 to your computer and use it in GitHub Desktop.
[MySQL] on duplicate key update 構文の UPDATE 句で VALUES 関数を使うと INSERT 句でセットしようとした値が取れる。
4.1.21-community-nt 71> USE test;
Query OK, 0 rows affected (0.00 sec)
4.1.21-community-nt 72> CREATE TABLE `test` (
-> `id` bigint(20) unsigned NOT NULL auto_increment,
-> `age` int(10) unsigned NOT NULL default '0',
-> PRIMARY KEY (`id`)
-> ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-> ;
Query OK, 0 rows affected (0.16 sec)
4.1.21-community-nt 73> INSERT INTO test VALUES(1, 10);
Query OK, 1 row affected (0.04 sec)
4.1.21-community-nt 74> SELECT * FROM test;
+----+-----+
| id | age |
+----+-----+
| 1 | 10 |
+----+-----+
1 row in set (0.00 sec)
4.1.21-community-nt 75> INSERT INTO test VALUES(1, 20) ON DUPLICATE KEY UPDATE age = VALUES(age);
Query OK, 2 rows affected (0.04 sec)
4.1.21-community-nt 76> SELECT * FROM test;
+----+-----+
| id | age |
+----+-----+
| 1 | 20 |
+----+-----+
1 row in set (0.00 sec)
4.1.21-community-nt 77> INSERT INTO test SET id = 1, age = 30 ON DUPLICATE KEY UPDATE age = VALUES(age);
Query OK, 2 rows affected (0.04 sec)
4.1.21-community-nt 78> SELECT * FROM test;
+----+-----+
| id | age |
+----+-----+
| 1 | 30 |
+----+-----+
1 row in set (0.00 sec)
4.1.21-community-nt 79> INSERT INTO test VALUES(1, 40) ON DUPLICATE KEY UPDATE age = VALUES(age) * 2;
Query OK, 2 rows affected (0.04 sec)
4.1.21-community-nt 80> SELECT * FROM test;
+----+-----+
| id | age |
+----+-----+
| 1 | 80 |
+----+-----+
1 row in set (0.00 sec)
@hatappo
Copy link
Author

hatappo commented Aug 12, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment