MySQL多表更新的一個坑

 

簡述

MySQL支持update t1,t2 set t1.a=2;這種語法,別的關係數據庫例如oracle和sql server都不支持。這種語法有時候寫起來挺方便,但他有一個坑。html

測試腳本

drop database fander; create database fander; use fander; create table t1(a int); create table t2(a int); insert into t1 value(1); select * from t1; update t1,t2 set t1.a=2; select * from t1;

測試結果

mysql> drop database fander;
create table t2(a int); insert into t1 value(1); select * from t1; update t1,t2 set t1.a=2; select * from t1;Query OK, 6 rows affected (0.35 sec) mysql> create database fander; Query OK, 1 row affected (0.00 sec) mysql> use fander; Database changed mysql> create table t1(a int); Query OK, 0 rows affected (0.11 sec) mysql> create table t2(a int); Query OK, 0 rows affected (0.23 sec) mysql> insert into t1 value(1); Query OK, 1 row affected (0.00 sec) mysql> select * from t1; +------+ | a | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> update t1,t2 set t1.a=2; Query OK, 0 rows affected (0.00 sec) Rows matched: 0 Changed: 0 Warnings: 0 mysql> select * from t1; +------+ | a | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> 

結果非預期

咱們想更新t1表的a列值爲2,但發現並無更新成功。。。mysql

緣由

由於t2是空表!sql

update t1,t2 set t1.a=2; 這個語句看起來修改與t2無關。t2是否空表應該不影響update行爲纔對呀?數據庫

https://dev.mysql.com/doc/refman/8.0/en/update.htmlmarkdown

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used.oracle

官方手冊其實寫明瞭,update語法是根據table_references,即關聯後的表,再作更新的。post

mysql> select * from t1; +------+ | a | +------+ | 1 | +------+ 1 row in set (0.00 sec) mysql> select * from t1,t2; Empty set (0.00 sec)

由於t2爲空表,t1的數據和空表數據作笛卡爾積,關聯表後則爲空。
update對這個空的table_references作更新,固然就找不到記錄,就沒有更新成功咯。測試

總結

這是一個坑,通常使用遇不到,但須要知道。ui

相關文章
相關標籤/搜索