MySQL - UPDATE JOIN 更新连接
要使用 MySQL 更新单个数据库表中的数据,可以使用 UPDATE 语句。但是,要更新多个数据库表中的数据,我们使用 UPDATE... JOIN 语句。
MySQL UPDATE... JOIN
通常,MySQL 中的JOIN用于根据匹配字段从多个表中获取行的组合。由于 UPDATE 语句仅修改单个表中的数据,因此我们使用 JOINS 将多个表合并为一个,然后进行更新。这也称为跨表修改。
语法
以下是 UPDATE...JOIN 语句的基本语法 -
UPDATE 表 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 | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
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 | DATE | CUSTOMER_ID | AMOUNT |
---|---|---|---|
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 | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
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 |
UPDATE... JOIN 语句,带 WHERE 子句
UPDATE... JOIN 查询中的 ON 子句用于对要更新的记录施加约束。此外,我们还可以使用 WHERE 子句来使约束更加严格。其语法如下:-
UPDATE table(s) SET column1 = value1, column2 = value2, ... FROM table1 JOIN table2 ON column3 = column4 WHERE condition;
示例
请观察以下查询。这里,我们尝试增加工资仅为 2000.00 的客户工资 -
UPDATE CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID SET SALARY = SALARY + 1000 WHERE CUSTOMERS.SALARY = 2000.00;
验证
正如我们在下面的 CUSTOMERS 表中看到的,工资为 2000 的客户获得了 1000 的加薪 -
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
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/Python 的 execute() 函数执行带有 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(); } // 更新连接 $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! "; } else { echo "Join could not be updated! "; } // 选择更新的值 $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! "; 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", }); //连接到 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://localhost: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 " + "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); 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 #建立连接 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