再論關聯子查詢更新

2021-09-10 09:30:14 字數 2605 閱讀 4293

之前使用oracle,遇到過2個表進行關聯子查詢更新的坑,沒有加exists從句,導致了不匹配的行設定成null,這個問題在mysql中也是一樣的。下面是測試

mysql> select * from test1;

+------+------+

| id | name |

+------+------+

| 1 | dddd |

| 2 | null |

| 3 | null |

+------+------+

3 rows in set (0.00 sec)

mysql> select * from test2;

+------+-------+

| id | name2 |

+------+-------+

| 1 | dddd |

+------+-------+

1 row in set (0.00 sec)

mysql> update test1 set name=(select name2 from test2 where test1.id=test2.id);

query ok, 3 rows affected (0.00 sec)

rows matched: 3 changed: 3 warnings: 0

mysql> select * from test1;

+------+--------+

| id | name |

+------+--------+

| 1 | ffffff |

| 2 | null |

| 3 | null |

+------+--------+

重置資料後

mysql> update test1 set name=(select name2 from test2 where test1.id=test2.id) where exists(select 1 from test2 where test1.id=test2.id);

query ok, 1 row affected (0.00 sec)

rows matched: 1 changed: 1 warnings: 0

mysql> select * from tes1;

error 1146 (42s02): table 'test.tes1' doesn't exist

mysql> select * from test1;

+------+------+

| id | name |

+------+------+

| 1 | ffff |

| 2 | bb |

| 3 | cc |

+------+------+

3 rows in set (0.01 sec)

主要就是test1中有匹配不上test2的id的記錄,這樣就會被設定為null,如果都有匹配的記錄那麼就是ok的,看下面的測試

mysql> insert into test1 values(1,'aa');

query ok, 1 row affected (0.00 sec)

mysql> insert into test1 values(2,'bb');

query ok, 1 row affected (0.00 sec)

mysql> insert into test1 values(3,'cc');

query ok, 1 row affected (0.00 sec)

mysql> select * from test2;

empty set (0.00 sec)

mysql> insert into test2 values(1,'eeee');

query ok, 1 row affected (0.00 sec)

mysql> insert into test2 values(2,'ffffff');

query ok, 1 row affected (0.00 sec)

mysql> insert into test2 values(3,'cc');

query ok, 1 row affected (0.01 sec)

mysql> update test1 set name=(select name2 from test2 where test1.id=test2.id);

query ok, 2 rows affected (0.01 sec)

rows matched: 3 changed: 2 warnings: 0

mysql> select * from test1;

+------+--------+

| id | name |

+------+--------+

| 1 | eeee |

| 2 | ffffff |

| 3 | cc |

+------+--------+

看到這種的id=3的記錄2個表是一致的,更新了2行,匹配了3行

mysql關聯子查詢 MySQL 關聯子查詢

mysql 關聯子查詢 關聯子查詢是指乙個包含對錶的引用的子查詢,該錶也顯示在外部查詢中。通俗一點來講,就是子查詢引用到了主查詢的資料資料。以乙個實際的例子來理解關聯子查詢 article 文章表 aidtitlecontentuid 文章1文章1正文內容.文章2文章2正文內容.文章3文章3正文內容...

利用帶關聯子查詢Update語句更新資料

update是t sql中再簡單不過的語句了,update table set column expression where condition 我們都會用到。但update的用法不僅於此,真正在開發的時候,靈活恰當地使用update可以達到事半功倍的效果。假定有表table1 a,b,c 和ta...

利用帶關聯子查詢Update語句更新資料

update是 t sql 中再簡單不過的語句了,update table set column expression where condition 我們都會用到。但 update 的用法不僅於此,真正在開發的時候,靈活恰當地使用 update 可以達到事半功倍的效果。假定有表table1 a,b...