MySQL - EXISTS 运算符



MySQL EXISTS 运算符

MySQL 中的 EXISTS 运算符检查表中是否存在记录。它用于 SELECT 语句的 WHERE 子句中,以验证子查询是否返回任何行。如果子查询返回至少一条记录,则返回 TRUE,否则返回 FALSE。

我们还可以将该运算符与 SQL 语句(例如 **SELECT、INSERT、UPDATE 和 DELETE**)一起使用,以验证子查询中记录的存在。

语法

以下是 MySQL 中 EXISTS 运算符的语法:

SELECT column1, column2, ...
FROM table_name
WHERE EXISTS (subquery);

示例

在执行 EXISTS 运算符之前,让我们首先创建两个名为 **CUSTOMERS** 和 **CARS** 的不同表。这里,我们正在创建 CUSTOMERS 表:

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

以下查询使用 INSERT INTO 语句向上面创建的表中添加 7 条记录:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 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 表中存在的所有记录:

SELECT * FROM CUSTOMERS;

以下是 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

让我们创建另一个名为 **CARS** 的表,其中包含客户 ID、汽车名称和价格等详细信息:

CREATE TABLE CARS (
   ID INT NOT NULL,
   NAME VARCHAR(20) NOT NULL,
   PRICE INT NOT NULL,
   PRIMARY KEY (ID)
);

以下查询将 3 条记录插入到上面创建的表中:

INSERT INTO CARS (ID, NAME, PRICE) VALUES
(2, 'Maruti Swift', 450000),
(4, 'VOLVO', 2250000),
(7, 'Toyota', 2400000);

执行以下查询以获取 CARS 表中存在的所有记录:

SELECT * FROM CARS;

以下是 CARS 表:

ID 姓名 (NAME) 价格 (PRICE)
2 Maruti Swift 450000
4 VOLVO 2250000
7 Toyota 2400000

EXISTS 运算符与 SELECT 语句

MySQL 中的 **SELECT** 语句用于从一个或多个表中检索数据。EXISTS 运算符可以与 SELECT 语句一起使用,以检查是否存在与特定条件匹配的行。

示例

现在,让我们获取汽车价格大于 2,000,000 的客户列表:

SELECT * FROM CUSTOMERS 
WHERE EXISTS 
(SELECT PRICE FROM CARS 
WHERE CARS.ID = CUSTOMERS.ID 
AND PRICE > 2000000);

输出

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

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

EXISTS 运算符与 UPDATE 语句

MySQL EXISTS 运算符可以与 UPDATE 语句一起使用,以根据另一个表中匹配行的存在来更新表中的行。

示例

在此查询中,我们使用 EXISTS 运算符将名称“Kushal”更新为所有其 ID 等于 CARS 表 ID 的客户:

UPDATE CUSTOMERS
SET NAME = 'Kushal'
WHERE EXISTS 
(SELECT NAME FROM CARS 
WHERE CUSTOMERS.ID = CARS.ID);

输出

我们可以看到,已修改了 3 行:

Query OK, 3 rows affected (0.01 sec)
Rows matched: 3  Changed: 3  Warnings: 0

验证

要验证更改是否已反映在 CUSTOMERS 表中,请执行以下查询:

SELECT * FROM CUSTOMERS;

CUSTOMERS 表显示如下:

ID 姓名 (NAME) 年龄 (AGE) 地址 (ADDRESS) 薪水 (SALARY)
1 Ramesh 32 Ahmedabad 2000.00
2 Kushal 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Kushal 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Kushal 24 Indore 10000.00

EXISTS 运算符与 DELETE 语句

MySQL EXISTS 运算符与 DELETE 语句一起使用,以根据子查询返回的行是否存在来删除表中的行。

示例

在这里,我们正在删除 CUSTOMERS 表中所有其 ID 等于 CARS 表中价格等于 2,250,000 的 ID 的记录:

DELETE FROM CUSTOMERS
WHERE EXISTS 
(SELECT * FROM CARS 
WHERE CARS.ID = CUSTOMERS.ID 
AND CARS.PRICE = 2250000);

输出

我们可以看到,已删除 1 行:

Query OK, 1 row affected (0.00 sec)

验证

我们可以使用以下查询验证更改是否已反映在 CUSTOMERS 表中:

SELECT * FROM CUSTOMERS;

输出

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

ID 姓名 (NAME) 年龄 (AGE) 地址 (ADDRESS) 薪水 (SALARY)
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

NOT 运算符与 EXISTS 运算符

如果我们在 MySQL 中将 NOT 与 EXISTS 运算符一起使用,它将选择一个表中不存在于另一个表中的记录。

语法

以下是 MySQL 中 NOT EXISTS 运算符的语法:

SELECT column1, column2, ...
FROM table_name
WHERE NOT EXISTS (subquery);

示例

在以下查询中,我们正在获取尚未购买任何汽车的客户的姓名:

SELECT * FROM CUSTOMERS
WHERE NOT EXISTS 
(SELECT * FROM CARS 
WHERE CUSTOMERS.ID = CARS.ID);

输出

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

ID 姓名 (NAME) 年龄 (AGE) 地址 (ADDRESS) 薪水 (SALARY)
1 Ramesh 32 Ahmedabad 2000.00
3 Kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00

使用客户端程序的 EXISTS 运算符

除了使用 MySQL 查询验证特定记录是否存在于 MySQL 表中之外,还可以使用客户端程序执行 EXISTS 操作。

语法

以下是该操作在各种编程语言中的语法:

要通过 PHP 程序验证特定记录是否存在于 MySQL 表中,我们需要使用 **mysqli** 函数 **query()** 执行带有 EXISTS 运算符的 SELECT 语句,如下所示:

$sql = "SELECT column1, column2, ... FROM table_name 
WHERE EXISTS (subquery)";
$mysqli->query($sql);

要通过 Node.js 程序验证特定记录是否存在于 MySQL 表中,我们需要使用 **mysql2** 库的 **query()** 函数执行带有 EXISTS 运算符的 SELECT 语句,如下所示:

sql= "SELECT column1, column2, ... FROM table_name 
WHERE EXISTS (subquery)";
con.query(sql);

要通过 Java 程序验证特定记录是否存在于 MySQL 表中,我们需要使用 **JDBC** 函数 **executeUpdate()** 执行带有 EXISTS 运算符的 SELECT 语句,如下所示:

String sql = "SELECT column1, column2, ... FROM table_name 
WHERE EXISTS (subquery)";
statement.executeQuery(sql);

要通过 Python 程序验证特定记录是否存在于 MySQL 表中,我们需要使用 MySQL **Connector/Python** 的 **execute()** 函数执行带有 EXISTS 运算符的 SELECT 语句,如下所示:

exists_query = "SELECT column1, column2, ... FROM table_name 
WHERE EXISTS (subquery)"
cursorObj.execute(exists_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 = "SELECT * FROM CUSTOMERS WHERE EXISTS (SELECT PRICE FROM CARS WHERE CARS.ID = CUSTOMERS.ID AND PRICE > 2000000);"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { printf("Table records: \n"); while($row = $result->fetch_assoc()) { printf("Id %d, Name: %s, Age: %d, Address %s, Salary %f", $row["ID"], $row["NAME"], $row["AGE"], $row["ADDRESS"], $row["SALARY"]); printf("\n"); } } else { printf('No record found.
'); } mysqli_free_result($result); $mysqli->close();

输出

获得的输出如下:

Table records:
Id 4, Name: Chaital, Age: 25, Address Mumbai, Salary 1200.000000
Id 7, Name: Muffy, Age: 24, Address Delhi, Salary 10000.000000   
var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  //Creating a Database
  sql = "create database TUTORIALS"
  con.query(sql);

  //Select database
  sql = "USE TUTORIALS"
  con.query(sql);

  //Creating CUSTOMERS table
  sql = "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));"
  con.query(sql);

  //Inserting Records
  sql = "INSERT INTO CUSTOMERS(ID, NAME, AGE, ADDRESS, SALARY) VALUES(1,'Ramesh', 32, 'Hyderabad',4000.00),(2,'Khilan', 25, 'Kerala', 8000.00),(3,'kaushik', 23, 'Hyderabad', 11000.00),(4,'Chaital', 25, 'Mumbai', 1200.00),(5,'Hardik', 27, 'Vishakapatnam', 10000.00),(6, 'Komal',29, 'Vishakapatnam', 7000.00),(7, 'Muffy',24, 'Delhi', 10000.00);"
  con.query(sql);

  //Creating CARS table
  sql = "CREATE TABLE CARS(ID INT NOT NULL,NAME VARCHAR(20) NOT NULL,PRICE INT NOT NULL,PRIMARY KEY (ID));"
  con.query(sql);
  
  //Inserting Records
  sql = "INSERT INTO CARS VALUES(2, 'Maruti Swift', 450000),(4, 'VOLVO', 2250000),(7, 'Toyota', 2400000);"
  con.query(sql);

  //Using EXISTS Operator
  sql = "SELECT * FROM CUSTOMERS WHERE EXISTS (SELECT PRICE FROM CARS WHERE CARS.ID = CUSTOMERS.ID AND PRICE > 2000000);"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log(result)
  });
});    

输出

生成的输出如下:

Connected!
--------------------------
[
  {
    ID: 4,
    NAME: 'Chaital',
    AGE: 25,
    ADDRESS: 'Mumbai',
    SALARY: '1200.00'
  },
  {
    ID: 7,
    NAME: 'Muffy',
    AGE: 24,
    ADDRESS: 'Delhi',
    SALARY: '10000.00'
  }
]          
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ExistsOperator {
  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...!");
            String sql = "SELECT * FROM CUSTOMERS WHERE EXISTS (SELECT PRICE FROM CARS WHERE CARS.ID = CUSTOMERS.ID AND PRICE > 2000000)";
            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 + ", Addresss: " + address + ", Salary: " + salary);
            }
    }catch(Exception e) {
      e.printStackTrace();
    }
  }
}                                   

输出

获得的输出如下所示:

Table records: 
Id: 4, Name: Chaitali, Age: 30, Addresss: Mumbai, Salary: 6500.00
Id: 7, Name: Muffy, Age: 24, Addresss: 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()
exists_query = f"""
SELECT * FROM CUSTOMERS WHERE EXISTS (SELECT PRICE FROM CARS WHERE 
CARS.ID = CUSTOMERS.ID AND PRICE > 2000000); """
cursorObj.execute(exists_query)
# Fetching all the rows that meet the criteria
filtered_rows = cursorObj.fetchall()
for row in filtered_rows:
    print(row)
cursorObj.close()
connection.close()                                

输出

以下是上述代码的输出:

(4, 'Chaital', 25, 'Mumbai', Decimal('1200.00'))
(7, 'Muffy', 24, 'Delhi', Decimal('10000.00'))   
广告