mysql implements merge into

http://blog.itpub.net/29989552/viewspace-2109761/



quote


MySQL does not have the merge into syntax of oracle and mssql, but there is an on duplicate key update syntax (not standard sql syntax) that can implement merge into syntax
. Experiment 1: Update all fields
mysql> select * from dup;
+---- --+--------+-------+
| id | name | phone |
+------+--------+------ -+
| 1 | wujian | 123 |
| 2 | xiay | 1234 |
| 3 | wangj | 12345 |
+------+--------+-------+
3 rows in set (0.00 sec)

mysql> select * from dupnew;
+------+------+-------+
| id | name | phone |
+------ +------+-------+
| 1 | xyr | 128 |
| 2 | sy | 0 |
| 5 | wsj | 8684 |
+------+----- -+-------+
3 rows in set (0.00 sec)

mysql> insert into dup(id,name,phone ) select * from dupnew on duplicate key update name=values(name);
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select * from dup;
+----+-------+-------+
| id | name | phone |
+----+-------+---- ---+
| 1 | xyr | 123 |
| 2 | sy | 1234 |
| 3 | wangj | 12345 |
| 5 | wsj | 8684 |
+----+-------+---- ---+
4 rows in set (0.00 sec)
Result: The table dupnew is updated to the table dup, if it exists, it will be updated, and if it does not exist, it will be inserted
Note : The id field is the primary key or UNIQUE index, otherwise only the dupnew table will be inserted All row data

Experiment 2: Update some fields
mysql> select * from dupagn;
+------+------+-------+
| id   | name | phone |
+------+------+-------+
|    1 | myy  |  1888 |
|   10 | wz   |   556 |
+------+------+-------+
2 rows in set (0.00 sec)

mysql> insert into dup(id,name) select id,name from dupagn on duplicate key update name=values(name);
Query OK, 3 rows affected (0.06 sec)
Records: 2  Duplicates: 1  Warnings: 0

mysql> select * from dup;
+----+-------+-------+
| id | name  | phone |
+----+-------+-------+
|  1 | myy   |   123 |
|  2 | sy    |  1234 |
|  3 | wangj | 12345 |
|  5 | wsj   |  8684 |
| 10 | wz    |  NULL |
+----+-------+-------+
5 rows in set (0.00 sec)
result: Only the name field is updated, but other fields in the inserted record are empty


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326071374&siteId=291194637