update 子查询 exists
要根据一个表的数据订正另一个表的部分,
例如,要订正xy1表的字段a为xy2表中的字段a的值,即,订正表xy1中id为1,2,3的记录的a字段的值,id为4,5的记录保持不变。可用uodate exists语句:
mysql> select * from xy1;
+----+------+------+
| id | a | b |
+----+------+------+
| 1 | t1 | 3 |
| 2 | t2 | 4 |
| 3 | t3 | 5 |
| 4 | t4 | 8 |
| 5 | t5 | 7 |
+----+------+------+
5 rows in set (0.07 sec)
mysql> select * from xy2;
+----+------+
| id | a |
+----+------+
| 1 | y10 |
| 2 | y20 |
| 3 | y30 |
+----+------+
3 rows in set (0.00 sec)
mysql> update xy1 set a=(select a from xy2 where xy1.id=xy2.id) where exists(select 1 from xy2 where xy1.id=xy2.id);
Query OK, 3 rows affected (0.01 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> select * from xy1;
+----+------+------+
| id | a | b |
+----+------+------+
| 1 | y10 | 3 |
| 2 | y20 | 4 |
| 3 | y30 | 5 |
| 4 | t4 | 8 |
| 5 | t5 | 7 |
+----+------+------+
5 rows in set (0.03 sec)
mysql> select * from xy2;
+----+------+
| id | a |
+----+------+
| 1 | y10 |
| 2 | y20 |
| 3 | y30 |
+----+------+
3 rows in set (0.03 sec)
猜你喜欢
转载自hnsyandy.iteye.com/blog/1916022
今日推荐
周排行