MySQL - 子查询



MySQL 子查询,也称为内部查询或嵌套查询,是另一个查询中的查询。它允许您根据另一个查询的结果从一个或多个表中检索数据。子查询可以用于 SQL 语句的各个部分,包括 SELECT、INSERT、UPDATE 和 DELETE。

使用 SELECT 语句的子查询

SELECT 语句中的子查询用于根据从子查询检索的值过滤主查询的结果。

语法

以下是 SELECT 语句中子查询的基本语法:

SELECT column1, column2, ...
FROM table1
WHERE columnN operator 
(SELECT column_name FROM table2 WHERE condition);

示例

首先,让我们使用以下查询创建一个名为 CUSTOMERS 的表:

CREATE TABLE CUSTOMERS(
   ID INT NOT NULL,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR(25) NOT NULL,
   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

以下查询从 CUSTOMERS 表中检索所有客户的薪水,其 ID 与同一表中的 ID 匹配:

SELECT SALARY FROM CUSTOMERS
WHERE ID IN
(SELECT ID FROM CUSTOMERS);

输出

上述查询的输出如下所示:

薪水 (SALARY)
2000.00
1500.00
2000.00
6500.00
8500.00
4500.00
10000.00

使用 INSERT 语句的子查询

我们还可以将子查询与 MySQL 中的 INSERT 语句一起使用。INSERT 语句将使用子查询返回的数据插入另一个表。

语法

以下是 INSERT 语句中子查询的基本语法:

INSERT INTO target_table (column1, column2, ...)
SELECT source_column1, source_column2, ...
FROM source_table
WHERE condition;

示例

在执行带有 INSERT 语句的子查询之前,让我们创建一个名为“CUSTOMERS_BKP”的表,其结构与 CUSTOMERS 表类似:

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

现在,让我们使用以下查询将 CUSTOMERS 表中的所有记录插入到 CUSTOMERS_BKP 表中:

INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);

输出

CUSTOMERS 表的记录已成功插入到 CUSTOMERS_BKP 表中:

Query OK, 7 rows affected (0.01 sec)
Records: 7  Duplicates: 0  Warnings: 0

验证

让我们使用以下 SELECT 语句验证 CUSTOMERS_BKP 表中是否包含记录:

SELECT * FROM CUSTOMERS_BKP;

正如我们在下表中看到的,CUSTOMERS 表中的所有记录都已插入到 CUSTOMERS_BKP 表中:

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

使用比较运算符的子查询

带有比较运算符的 MySQL 子查询允许我们在另一个查询中使用查询,并使用比较运算符将其结果与外部查询进行比较。

语法

以下是带有比较运算符的子查询的基本语法:

SELECT column_name [, column_name ]
FROM   table1 [, table2 ]
WHERE  column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE] .....)

示例

以下查询从 CUSTOMERS_BKP 表中检索所有年龄大于 23 的 CUSTOMERS 并返回其 ID。

SELECT * FROM CUSTOMERS_BKP
WHERE ID IN (SELECT ID FROM CUSTOMERS_BKP
WHERE AGE > 23);

输出

上述查询的输出如下所示:

ID 姓名 (NAME) 年龄 (AGE) 地址 (ADDRESS) 薪水 (SALARY)
2 Khilan 25 Delhi 1500.00
4 Chaitali 25 Mumbai 6500.00
7 Muffy 24 Indore 10000.00

使用 IN 或 NOT IN 运算符的子查询

带有 IN/NOT IN 运算符的 MySQL 子查询用于根据一个查询的值是否与另一个查询的值匹配来过滤数据:

  • IN 匹配列表中的任何值

  • NOT IN 排除列表中的任何值。

示例

以下查询从 CUSTOMERS 表中检索所有地址**不是**“Hyderabad”的记录,方法是将其与 CUSTOMERS_BKP 表中的地址进行比较:

SELECT * FROM CUSTOMERS
WHERE ADDRESS NOT IN (
SELECT ADDRESS FROM CUSTOMERS_BKP WHERE ADDRESS = "Hyderabad");

输出

以下是上述查询的输出:

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
7 Muffy 24 Indore 10000.00

示例

现在,以下查询使用子查询从 CUSTOMERS_BKP 表中提取所有与“Hyderabad”匹配的地址,从而从 CUSTOMERS 表中检索地址为“Hyderabad”的所有行:

SELECT * FROM CUSTOMERS
WHERE ADDRESS IN (
SELECT ADDRESS FROM CUSTOMERS_BKP WHERE ADDRESS = "Hyderabad");

输出

执行给定查询后,输出将显示如下:

ID 姓名 (NAME) 年龄 (AGE) 地址 (ADDRESS) 薪水 (SALARY)
6 Komal 22 Hyderabad 4500.00

使用客户端程序的子查询

我们还可以使用客户端程序执行子查询。

语法

要通过 PHP 程序使用子查询提取数据,我们需要使用mysqli 函数query()执行“SELECT”语句,如下所示:

$sql = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)";
$mysqli->query($sql);

要通过 JavaScript 程序使用子查询提取数据,我们需要使用mysql2 库的query()函数执行“SELECT”语句,如下所示:

sql = "SELECT NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)";
con.query(sql);

要通过 Java 程序使用子查询提取数据,我们需要使用JDBC 函数executeQuery()执行“SELECT”语句,如下所示:

String sql = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)";
statement.executeQuery(sql);

要通过 Python 程序使用子查询提取数据,我们需要使用MySQL Connector/Pythonexecute()函数执行“SELECT”语句,如下所示:

sub_query = "SELECT SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS)"
cursorObj.execute(sql)

示例

以下是程序:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); $sql = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)"; printf("Table records: \n"); if($result = $mysqli->query($sql)){ while($row = mysqli_fetch_array($result)){ printf("Id: %d, NAME: %s, AGE: %d, ADDRESS: %s, SALARY: %f", $row['ID'], $row['NAME'], $row['AGE'], $row['ADDRESS'], $row['SALARY']); printf("\n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

输出

获得的输出如下所示:

Table records:
Id: 4, NAME: Chaitali, AGE: 25, ADDRESS: Mumbai, SALARY: 6500.000000
Id: 5, NAME: Hardik, AGE: 27, ADDRESS: Bhopal, SALARY: 8500.000000
Id: 6, NAME: Komal, AGE: 22, ADDRESS: Hyderabad, SALARY: 4500.000000
Id: 7, NAME: Muffy, AGE: 24, ADDRESS: Indore, SALARY: 10000.000000  
NodeJS program
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);
 //create table
 sql = "SELECT NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)";
 con.query(sql, function(err, result){
    console.log("Subquery executed successfully...!");
    console.log("Table records: ")
    if (err) throw err;
    console.log(result);
    });
});  

输出

获得的输出如下所示:

Subquery executed successfully...!
Table records:
[
  { NAME: 'Chaitali', AGE: 25, ADDRESS: 'Mumbai', SALARY: '6500.00' },
  { NAME: 'Hardik', AGE: 27, ADDRESS: 'Bhopal', SALARY: '8500.00' },
  { NAME: 'Komal', AGE: 22, ADDRESS: 'Hyderabad', SALARY: '4500.00' },
  { NAME: 'Muffy', AGE: 24, ADDRESS: 'Indore', SALARY: '10000.00' }
]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SubQuery {
  public static void main(String[] args) {
    String url = "jdbc:mysql://127.0.0.1:3306/TUTORIALS";
    String user = "root";
    String password = "password";
    ResultSet rs;
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            //create table
            String sql = "SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 2000)";
            rs = st.executeQuery(sql);
            System.out.println("Table records: ");
            while(rs.next()) {
              String id = rs.getString("id");
              String name = rs.getString("name");
              String age = rs.getString("age");
              String address = rs.getString("address");
              String salary = rs.getString("salary");
              System.out.println("Id: " + id + ", Name: " + name + ", Age: " + age + ", Address: " + address + ", Salary: " + salary);
            }
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
}

输出

获得的输出如下所示:

Table records: 
Id: 4, Name: Chaitali, Age: 25, Address: Mumbai, Salary: 6500.00
Id: 5, Name: Hardik, Age: 27, Address: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Address: Hyderabad, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Address: Indore, Salary: 10000.00
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
# Subquery to fetch the salaries of all customers whose ID is present in the same table
sub_query = f"""
SELECT SALARY FROM CUSTOMERS
WHERE ID IN
(SELECT ID FROM CUSTOMERS);
"""
cursorObj.execute(sub_query)
# Fetching all the rows that meet the criteria
filtered_rows = cursorObj.fetchall()
for row in filtered_rows:
    print(row)
cursorObj.close()
connection.close()

输出

获得的输出如下所示:

(Decimal('2000.00'),)
(Decimal('1500.00'),)
(Decimal('2000.00'),)
(Decimal('6500.00'),)
(Decimal('8500.00'),)
(Decimal('4500.00'),)
(Decimal('10000.00'),)
广告