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://127.0.0.1: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
广告