SQL Update與Join


SQL UPDATE JOIN可使用一個表和連線條件來更新另一個表。

假設有一個客戶表,更新包含來自其他系統的最新客戶詳細資訊的客戶表。比如要用最新資料來更新客戶表。 在這種情況下,將使用客戶ID上的連線在目標表和源表之間執行連線。

下面來看看SQL UPDATEJOIN語句的查詢語法。

UPDATE customer_table  
INNER JOIN  
Customer_table  
ON customer_table.rel_cust_name = customer_table.cust_id  
SET customer_table.rel_cust_name = customer_table.cust_name

如何在SQL UPDATE語句中使用JOIN使用多個表?

這裡使用兩個表:table1table2

建立table1表 -

CREATE TABLE table1 (column1 INT, column2 INT, column3 VARCHAR (100));
INSERT INTO table1 (column1, column2, column3)
SELECT 1, 11, 'FIRST'  
UNION ALL  
SELECT 11,12, 'SECOND'  
UNION ALL   
SELECT 21, 13, 'THIRD'  
UNION ALL   
SELECT 31, 14, 'FOURTH';

建立table2表 -

CREATE TABLE table2 (column1 INT, column2 INT, column3 VARCHAR (100));
INSERT INTO table2 (column1, column2, column3)
SELECT 1, 21, 'TWO-ONE'  
UNION ALL  
SELECT 11, 22, 'TWO-TWO'  
UNION ALL   
SELECT 21, 23, 'TWO-THREE'  
UNION ALL   
SELECT 31, 24, 'TWO-FOUR';

接下來,檢視表中的內容 -

SELECT * FROM table1;

執行上面範例程式碼,得到以下結果 -

mysql> SELECT * FROM table1;
+---------+---------+---------+
| column1 | column2 | column3 |
+---------+---------+---------+
|       1 |      11 | FIRST   |
|      11 |      12 | SECOND  |
|      21 |      13 | THIRD   |
|      31 |      14 | FOURTH  |
+---------+---------+---------+
4 rows in set
SELECT * FROM table2;

執行上面範例程式碼,得到以下結果 -

mysql> SELECT * FROM table2;
+---------+---------+-----------+
| column1 | column2 | column3   |
+---------+---------+-----------+
|       1 |      21 | TWO-ONE   |
|      11 |      22 | TWO-TWO   |
|      21 |      23 | TWO-THREE |
|      31 |      24 | TWO-FOUR  |
+---------+---------+-----------+
4 rows in set

table2中有兩行:column1的值是2131,假設想要將table1中的值更新為table2column12131行的值。

僅更新column2column3的值。

最簡單和最常用的方法是在update語句中使用join子句並在update語句中使用多個表。

UPDATE table1 t1
LEFT JOIN  table2 t2
ON t1.column1 = t2.column1
SET t1.column2 = t2.column2,  
t1.column3 = t2.column3 
where t1.column1 in(21,31);

執行以下語句,檢視更新結果 -

mysql> select * from table1;
+---------+---------+-----------+
| column1 | column2 | column3   |
+---------+---------+-----------+
|       1 |      11 | FIRST     |
|      11 |      12 | SECOND    |
|      21 |      23 | TWO-THREE |
|      31 |      24 | TWO-FOUR  |
+---------+---------+-----------+
4 rows in set