MySQL - IN 运算符



MySQL IN 运算符

MySQL 中的IN 运算符是一个逻辑运算符,它允许我们检查数据库中的值是否出现在 SQL 语句中指定的列表中。

IN 运算符可以与 SQL 中的任何数据类型一起使用。它用于根据指定的值过滤数据库表中的数据。它返回指定列值与列表中任何一个值匹配的所有行。

当您想要选择与特定值集中的一个值匹配的所有行时,IN 运算符非常有用。当您想要选择与多个条件中的任何一个匹配的所有行时,OR 运算符很有用。

在某些情况下,我们可能会使用多个 OR 语句在 SELECT、DELETE、UPDATE 或 INSERT 语句中包含多个条件。您可以使用 IN 子句替换多个 OR 条件。

语法

以下是 IN 运算符的基本语法:

WHERE COLUMN_NAME IN (value1, value2, value3,....);

示例

为了理解IN 子句,让我们首先使用以下 CREATE TABLE 语句创建一个名为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

使用以下查询,从 CUSTOMERS 表中检索姓名为“Khilan”、“Hardik”、“Muffy”的记录:

SELECT * FROM CUSTOMERS 
WHERE NAME IN ('Khilan', 'Hardik', 'Muffy');

输出

获得的输出如下:

ID 姓名 年龄 地址 薪水
2 Khilan 25 Delhi 1500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00

UPDATE 语句中的 IN 运算符

MySQL UPDATE 语句用于修改数据库表中的现有数据。因此,我们也可以在 UPDATE 语句中使用 IN 运算符(作为过滤器)来更新现有行。

示例

在这个例子中,让我们通过将年龄为“25”或“27”的客户的年龄值设置为“30”来更新他们的记录:

UPDATE CUSTOMERS 
SET AGE = 30 WHERE AGE IN (25, 27);

验证

我们可以使用 SELECT 语句检索表的内容来验证更改是否反映在表中。使用以下查询显示 CUSTOMERS 表中更新的记录:

ID 姓名 年龄 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 30 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 30 Mumbai 6500.00
5 Hardik 30 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

MySQL NOT IN 运算符

为了否定一个条件,我们使用 NOT 运算符。MySQL IN 运算符可以与 NOT 运算符结合使用,以在 WHERE 子句中排除特定值。

换句话说,将检查表达式中缺少列表的情况。

语法

以下是 NOT IN 运算符的基本语法:

WHERE column_name NOT IN (value1, value2,...);

示例

现在,我们尝试显示 CUSTOMERS 表中的所有记录,其中 AGE 不等于“25”、“23”和“22”:

SELECT * FROM CUSTOMERS 
WHERE AGE NOT IN (25, 23, 22);

输出

获得的输出为:

ID 姓名 年龄 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00

使用 IN 运算符比较值

我们还可以使用 IN 运算符和列名来将一列的值与另一列进行比较。它用于选择给定列存在特定值的那些行。

示例

在下面的查询中,我们尝试选择包含 SALARY 列值的那些行:

SELECT * FROM CUSTOMERS 
WHERE 2000 IN (SALARY);

输出

获得以下输出:

ID 姓名 年龄 地址 薪水
1 Ramesh 32 Ahmedabad 2000.00
3 Kaushik 23 Kota 2000.00

MySQL 使用 IN 运算符的子查询

我们可以使用带有 IN 运算符的子查询来返回单个列中的记录。这意味着 SELECT 列列表中不能包含多个列在指定的子查询中。

语法

指定查询的 IN 运算符的基本语法如下:

WHERE column_name IN (subquery);

示例

在下面给出的查询中,我们显示 CUSTOMERS 表中的所有记录,其中客户的 NAME 是通过 SALARY 大于 2000 获得的:

SELECT * FROM CUSTOMERS 
WHERE NAME IN (
   SELECT NAME FROM CUSTOMERS 
   WHERE SALARY > 2000
);

输出

获得以下输出:

ID 姓名 年龄 地址 薪水
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

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

除了直接在MySQL服务器上执行IN运算符外,我们还可以使用客户端程序执行它。

语法

以下是使用各种编程语言的IN运算符语法:

要在PHP程序中通过MySQL表使用IN运算符,我们需要使用mysqli连接器提供的名为query()的函数执行带有IN的SQL语句。

$sql = "SELECT COLUMN1, COLUMN2, ... FROM TABLE_NAME 
WHERE COLUMN_NAME IN (VALUE1, VALUE2, ...)";
$mysqli->query($sql);

要在JavaScript程序中通过MySQL表使用IN运算符,我们需要使用mysql2连接器提供的名为query()的函数执行带有IN的SQL语句。

sql= "SELECT columns FROM table_name 
WHERE column_name IN (value1, value2, value3, ...)";  
con.query(sql);

要在Java程序中通过MySQL表使用IN运算符,我们需要使用JDBC类型4驱动程序提供的名为executeQuery()的函数执行带有IN的SQL语句。

String sql = "SELECT COLUMN(S) FROM TABLE_NAME 
WHERE COLUMN_NAME IN(VALUE1, VALUE2, VALUE3,...)";
statement.executeQuery(sql);

要在Python程序中通过MySQL表使用IN运算符,我们需要使用MySQL Connector/Python提供的名为execute()的函数执行带有IN的SQL语句。

in_query = "SELECT column1, column2, ... FROM table_name 
WHERE column_name IN (value1, value2, value3, ...)"
cursorObj.execute(in_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 tutorials_tbl WHERE tutorial_author IN('John', 'Sanjay', 'Mahesh')"; $result = $mysqli->query($sql); if ($result->num_rows > 0) { printf("Table records: \n"); while($row = $result->fetch_assoc()) { printf("Id %d, Title: %s, Author: %s, S_date %s", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); printf("\n"); } } else { printf('No record found.
'); } mysqli_free_result($result); $mysqli->close();

输出

获得的输出如下:

Table records:
Id 3, Title: JAVA Tutorial, Author: Sanjay, S_date 2007-05-21
Id 4, Title: Learn PHP, Author: John Poul, S_date 2023-07-26
Id 6, Title: Learn MySQL, Author: Mahesh, S_date 2023-07-26      
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 table
  sql = "CREATE TABLE IF NOT EXISTS employee_tbl(id INT NOT NULL, name VARCHAR(100) NOT NULL, work_date DATE, daily_typing_pages INT);"
  con.query(sql);

  //Inserting Records
  sql = "INSERT INTO employee_tbl(id, name, work_date, daily_typing_pages) VALUES(1, 'John', '2007-01-24', 250), (2, 'Ram', '2007-05-27', 220), (3, 'Jack', '2007-05-06', 170), (3, 'Jack', '2007-04-06', 100), (4, 'Jill', '2007-04-06', 220),(5, 'Zara', '2007-06-06', 300),(5, 'Zara', '2007-02-06', 350);"
  con.query(sql);

  //Using IN Operator
  sql = "SELECT * FROM employee_tbl WHERE daily_typing_pages IN ( 250, 220, 170 );"
  con.query(sql, function(err, result){
    if (err) throw err
    console.log(result)
  });
});    

输出

生成的输出如下:

Connected!
--------------------------
[
  {
    id: 1,
    name: 'John',
    work_date: 2007-01-23T18:30:00.000Z,
    daily_typing_pages: 250
  },
  {
    id: 2,
    name: 'Ram',
    work_date: 2007-05-26T18:30:00.000Z,
    daily_typing_pages: 220
  },
  {
    id: 3,
    name: 'Jack',
    work_date: 2007-05-05T18:30:00.000Z,
    daily_typing_pages: 170
  },
  {
    id: 4,
    name: 'Jill',
    work_date: 2007-04-05T18:30:00.000Z,
    daily_typing_pages: 220
  }
]      
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class InOperator {
    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 = "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))";
            st.execute(sql);
            System.out.println("Table created successfully...!");
            //now lets insert some records
            String sql1 = "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, 'MP', 4500.00 ), (7, 'Muffy', 24, 'Indore', 10000.00 )";
            st.execute(sql1);
            System.out.println("Records inserted successfully....!");
            //display records
            String sql2 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql2);
            System.out.println("Table records before update: ");
            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);
            }
            //let use IN operator with where clause to update records
            String sql3 = "UPDATE CUSTOMERS SET AGE = 30 WHERE AGE IN (25, 27)";
            st.executeUpdate(sql3);
            //display table records after update
            String sql4 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql4);
            System.out.println("Table records before update: ");
            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 created successfully...!
Records inserted successfully....!
Table records before update: 
Id: 1, Name: Ramesh, Age: 32, Addresss: Ahmedabad, Salary: 2000.00
Id: 2, Name: Khilan, Age: 25, Addresss: Delhi, Salary: 1500.00
Id: 3, Name: kaushik, Age: 23, Addresss: Kota, Salary: 2000.00
Id: 4, Name: Chaitali, Age: 25, Addresss: Mumbai, Salary: 6500.00
Id: 5, Name: Hardik, Age: 27, Addresss: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Addresss: MP, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Addresss: Indore, Salary: 10000.00
Table records before update: 
Id: 1, Name: Ramesh, Age: 32, Addresss: Ahmedabad, Salary: 2000.00
Id: 2, Name: Khilan, Age: 30, Addresss: Delhi, Salary: 1500.00
Id: 3, Name: kaushik, Age: 23, Addresss: Kota, Salary: 2000.00
Id: 4, Name: Chaitali, Age: 30, Addresss: Mumbai, Salary: 6500.00
Id: 5, Name: Hardik, Age: 30, Addresss: Bhopal, Salary: 8500.00
Id: 6, Name: Komal, Age: 22, Addresss: MP, Salary: 4500.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'
)
# Creating a cursor object 
cursorObj = connection.cursor()
in_query = f"""SELECT * FROM customers
WHERE id IN (2, 4, 6)"""
cursorObj.execute(in_query)
# Fetching all rows that meet the criteria
filtered_rows = cursorObj.fetchall()
for row in filtered_rows:
    print(row)
cursorObj.close()
connection.close()                                   

输出

以下是上述代码的输出:

(2, 'Khilan', 25, 'Kerala', Decimal('8000.00'))
(4, 'Chaital', 25, 'Mumbai', Decimal('1200.00'))
(6, 'Komal', 29, 'Vishakapatnam', Decimal('7000.00'))  
mysql-useful-functions.htm
广告