MySQL - 刪除連線



MySQL 中簡單的刪除操作可以對錶中的單個實體或多個實體執行。但是,如果此刪除操作需要對多個表的多個實體執行怎麼辦?這就是連線發揮作用的地方。

MySQL DELETE... JOIN

正如我們之前在本教程中討論的那樣,連線用於透過組合這些表的列(基於公共欄位)來檢索來自兩個或多個表的記錄。此合併的資料可以被刪除,所有更改都反映在原始表中。

語法

以下是 MySQL 中 DELETE... JOIN 語句的基本語法:

DELETE table(s)
FROM table1 JOIN table2
ON table1.common_field = table2.common_field;

在執行刪除操作時,可以使用任何連線子句(INNER JOIN、LEFT JOIN、RIGHT JOIN 等)。

示例

在此示例中,我們首先建立一個名為 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);

表將被建立為:

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);

表顯示如下:

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

刪除操作是透過對這些表應用DELETE... JOIN查詢來執行的。

DELETE a
FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
ON a.ID = b.CUSTOMER_ID;

驗證

要驗證更改是否反映在表中,可以使用 SELECT 語句打印表。

ID 姓名 年齡 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

帶有 WHERE 子句的 DELETE... JOIN

DELETE... JOIN 查詢中的ON子句用於對記錄應用約束。此外,我們還可以使用 WHERE 子句使過濾更嚴格。觀察下面的查詢;在這裡,我們嘗試刪除 CUSTOMERS 表中薪水低於 2000.00 盧比的客戶記錄。

DELETE a
FROM CUSTOMERS AS a INNER JOIN ORDERS AS b
ON a.ID = b.CUSTOMER_ID
WHERE a.SALARY < 2000.00;

驗證

為了驗證更改是否反映在原始表中,我們將使用 SELECT 語句。

刪除後,CUSTOMERS 表如下所示:

ID 姓名 年齡 地址 薪水
1 Ramesh 32 Ahmedabad 2000.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

使用客戶端程式進行刪除連線

除了使用 MySQL 查詢連線兩個或多個表之外,我們還可以使用客戶端程式執行 Delete Join 操作。

語法

要透過 PHP 程式執行 Delete Join,我們需要使用mysqli函式query()執行帶有 JOIN 子句的 DELETE 語句,如下所示:

$sql = 'DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author';
$mysqli->query($sql);

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

sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
con.query(sql);  

要透過 Java 程式執行 Delete Join,我們需要使用JDBC函式executeUpdate()執行帶有 JOIN 子句的 DELETE 語句,如下所示:

String sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
statement.executeUpdate(sql);

要透過 python 程式執行 Delete Join,我們需要使用MySQL Connector/Pythonexecute()函式執行帶有 JOIN 子句的 DELETE 語句,如下所示:

delete_join_query = "DELETE a FROM CUSTOMERS AS a INNER JOIN ORDERS AS b ON a.ID = b.CUST_ID"
cursorObj.execute(delete_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(); } // printf('Connected successfully.
'); $sql = 'DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author'; if ($mysqli->query($sql)) { printf("Join deleted successfully!.
"); } if ($mysqli->errno) { printf("Join could not be deleted !.
", $mysqli->error); } $mysqli->close();

輸出

獲得的輸出如下:

Join deleted successfully!.  
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);

  //Delete Join
  sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});  

輸出

產生的輸出如下所示:

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 2,
  insertId: 0,
  info: '',
  serverStatus: 34,
  warningStatus: 0,
  changedRows: 0
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DeleteJoin {
   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 Delete JOIN...!;
         String sql = "DELETE tutorials_tbl, tcount_tbl FROM tcount_tbl INNER JOIN tutorials_tbl ON tcount_tbl.tutorial_author = tutorials_tbl.tutorial_author";
         statement.executeUpdate(sql);
         System.out.println("JOIN Deleted successfully...!");
         connection.close();
      } catch (Exception e) {
         System.out.println(e);
      }
   }
}

輸出

獲得的輸出如下所示:

Connected successfully...!
JOIN Deleted successfully...! 
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
delete_join_query = f"""DELETE a FROM CUSTOMERS AS a INNER JOIN ORDERS AS b ON a.ID = b.CUST_ID"""
cursorObj.execute(delete_join_query)
connection.commit()
print("deleted succesfully")
cursorObj.close()
connection.close()

輸出

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

deleted successfully
廣告