MySQL - 更新聯接



要使用 MySQL 更新單個數據庫表中輸入的資料,可以使用 UPDATE 語句。但是,要更新多個數據庫表中的資料,我們使用 UPDATE... JOIN 語句。

MySQL UPDATE... JOIN

通常,MySQL 中的聯接用於根據匹配欄位獲取多個表中行的組合。並且由於UPDATE語句僅修改單個表中的資料,因此我們使用聯接將多個表組合成一個,然後更新它們。這也被稱為跨表修改。

語法

以下是 UPDATE... JOIN 語句的基本語法:

UPDATE table(s)
SET column1 = value1, column2 = value2, ...
FROM table1 
JOIN table2 ON column3 = column4;

示例

讓我們首先建立一個名為 CUSTOMERS 的表,其中包含客戶的個人詳細資訊,包括他們的姓名、年齡、地址和薪水等。

CREATE TABLE CUSTOMERS (
   ID INT NOT NULL,
   NAME VARCHAR (20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),       
   PRIMARY KEY (ID)
);

現在使用 INSERT 語句將值插入此表,如下所示:

INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

將建立 CUSTOMERS 表,如下所示:

ID 姓名 年齡 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

讓我們建立另一個名為 ORDERS 的表,其中包含所下訂單的詳細資訊以及訂單日期。

CREATE TABLE ORDERS (
   OID INT NOT NULL,
   DATE VARCHAR (20) NOT NULL,
   CUSTOMER_ID INT NOT NULL,
   AMOUNT DECIMAL (18, 2)
);

使用 INSERT 語句,將值插入此表,如下所示:

INSERT INTO ORDERS VALUES 
(102, '2009-10-08 00:00:00', 3, 3000.00),
(100, '2009-10-08 00:00:00', 3, 1500.00),
(101, '2009-11-20 00:00:00', 2, 1560.00),
(103, '2008-05-20 00:00:00', 4, 2060.00);

ORDERS 表顯示如下:

OID 日期 客戶 ID 金額
102 2009-10-08 00:00:00 3 3000.00
100 2009-10-08 00:00:00 3 1500.00
101 2009-11-20 00:00:00 2 1560.00
103 2008-05-20 00:00:00 4 2060.00

使用以下UPDATE... JOIN查詢跨修改多個表(CUSTOMERS 和 ORDERS):

UPDATE CUSTOMERS
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
SET CUSTOMERS.SALARY = CUSTOMERS.SALARY + 1000;

驗證

如下面的 CUSTOMERS 表所示,我們在上述查詢中執行的更改已反映出來:

ID 姓名 年齡 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 2500.00
3 Kaushik 23 Kota 3000.00
4 Chaitali 25 Mumbai 7500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

使用 WHERE 子句的 UPDATE... JOIN

UPDATE... JOIN 查詢中的 ON 子句用於對要更新的記錄應用約束。除此之外,我們還可以使用 WHERE 子句使約束更嚴格。其語法如下:

UPDATE table(s)
SET column1 = value1, column2 = value2, ...
FROM table1 
JOIN table2 ON column3 = column4
WHERE condition;

示例

觀察下面的查詢。在這裡,我們試圖增加僅賺取 2000.00 的 CUSTOMERS 的薪水:

UPDATE CUSTOMERS 
LEFT JOIN ORDERS 
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID 
SET SALARY = SALARY + 1000 
WHERE CUSTOMERS.SALARY = 2000.00;

驗證

如下面的 CUSTOMERS 表所示,薪水為 2000 的 CUSTOMERS 增加了 1000:

ID 姓名 年齡 地址 薪水
1 Ramesh 32 Ahmedabad 3000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 3000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

使用客戶端程式更新聯接

除了使用 MySQL 查詢聯接兩個或多個表之外,我們還可以使用客戶端程式執行更新聯接操作。

語法

要透過 PHP 程式執行更新聯接,我們需要使用mysqli函式query()執行帶有 JOIN 子句的 UPDATE 語句,如下所示:

$sql = 'UPDATE tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author 
SET tcount_tbl.tutorial_count = tcount_tbl.tutorial_count + 100';
$mysqli->query($sql);

要透過 JavaScript 程式執行更新聯接,我們需要使用mysql2庫的query()函式執行帶有 JOIN 子句的 UPDATE 語句,如下所示:

sql = "UPDATE Customers c JOIN Orders o ON c.ID = o.CUSTOMER_ID  SET c.SALARY = c.SALARY + o.AMOUNT";
con.query(sql);  

要透過 Java 程式執行更新聯接,我們需要使用JDBC函式executeUpdate()執行帶有 JOIN 子句的 UPDATE 語句,如下所示:

String sql = "UPDATE tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author 
SET tcount_tbl.tutorial_count = tcount_tbl.tutorial_count + 100";
statement.executeUpdate(sql);

要透過 Python 程式執行更新聯接,我們需要使用MySQL Connector/Pythonexecute()函式執行帶有 JOIN 子句的 UPDATE 語句,如下所示:

update_join_query = "UPDATE Customers c JOIN Orders o ON c.ID = o.CUST_ID SET c.SALARY = c.SALARY + o.AMOUNT"
cursorObj.execute(update_join_query)

示例

以下是程式:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // Updating Join $sql = 'UPDATE tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author SET tcount_tbl.tutorial_count = tcount_tbl.tutorial_count + 100'; if ($mysqli->query($sql)) { echo "Join updated successfully! \n"; } else { echo "Join could not be updated! \n"; } // Selecting the updated value $update_res = 'SELECT a.tutorial_author, b.tutorial_count FROM tutorials_tbl a INNER JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author'; $result = $mysqli->query($update_res); if ($result->num_rows > 0) { echo "Updated tutorial_count! \n"; while ($row = $result->fetch_assoc()) { printf("Author: %s, Count: %d", $row["tutorial_author"], $row["tutorial_count"]); printf("
"); } } else { printf('No record found.
'); } mysqli_free_result($result); $mysqli->close();

輸出

獲得的輸出如下:

Join updated successfully!
Updated tutorial_count!
Author: John Paul, Count: 101
Author: Sanjay, Count: 101   
var mysql = require("mysql2");
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
}); //Connecting to MySQL

con.connect(function (err) {
  if (err) throw err;
  //   console.log("Connected successfully...!");
  //   console.log("--------------------------");
  sql = "USE TUTORIALS";
  con.query(sql);

  //UPDATE JOIN
  sql = "UPDATE Customers c JOIN Orders o ON c.ID = o.CUSTOMER_ID  SET c.SALARY = c.SALARY + o.AMOUNT";

  //displaying the updated data along with ID;
  sql =
    "SELECT c.ID, c.SALARY FROM Customers c INNER JOIN Orders o  ON c.ID = o.CUSTOMER_ID";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});    

輸出

產生的輸出如下:

[
  { ID: 3, SALARY: '5000.00' },
  { ID: 3, SALARY: '5000.00' },
  { ID: 2, SALARY: '3060.00' },
  { ID: 4, SALARY: '8560.00' }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class UpdateJoin {
   public static void main(String[] args) {
      String url = "jdbc:mysql://:3306/TUTORIALS";
      String username = "root";
      String password = "password";
      try {
         Class.forName("com.mysql.cj.jdbc.Driver");
         Connection connection = DriverManager.getConnection(url, username, password);
         Statement statement = connection.createStatement();
         System.out.println("Connected successfully...!");

         //MySQL Update JOIN...!;
         String sql = "UPDATE tcount_tbl\n" + 
         "INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author\n" + 
         "SET tcount_tbl.tutorial_count = tcount_tbl.tutorial_count + 100\n";
         statement.executeUpdate(sql);
         System.out.println("tutorial_count updated successfully...!");

         //fetch the records...!;
         ResultSet resultSet = statement.executeQuery("SELECT a.tutorial_author, b.tutorial_count FROM tutorials_tbl a INNER JOIN tcount_tbl b ON a.tutorial_author = b.tutorial_author");
         while (resultSet.next()){
            System.out.println(resultSet.getString(1)+ " "+ resultSet.getInt(2));
         }
         connection.close();
      } catch (Exception e) {
         System.out.println(e);
      }
   }
}  

輸出

獲得的輸出如下所示:

Connected successfully...!
tutorial_count updated successfully...!
John Paul 201
Sanjay 201
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
update_join_query = f"""UPDATE Customers c JOIN Orders o ON c.ID = o.CUST_ID SET c.SALARY = c.SALARY + o.AMOUNT"""
cursorObj.execute(update_join_query)
connection.commit()
print("updated successfully")
cursorObj.close()
connection.close()

輸出

以下是上述程式碼的輸出:

updated successfully
廣告