MySQL - BETWEEN 运算符



MySQL BETWEEN 运算符

MySQL 中的BETWEEN 运算符是 SQL 提供的一个逻辑运算符,用于限制要检索数据值的范围。检索到的值可以是整数、字符或日期。

可以使用BETWEEN 运算符替换“大于等于 AND 小于等于”条件的组合。

让我们通过以下示例表更好地理解:

between

语法

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

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

这里,

  • value1 是范围的起始值。
  • value2 是范围的结束值(包含)。

示例

首先,让我们使用以下查询创建一个名为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 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

现在,我们使用 BETWEEN 运算符检索 AGE(数值数据)介于 20 和 25 之间的 CUSTOMERS 的详细信息:

SELECT * FROM CUSTOMERS 
WHERE AGE BETWEEN 20 AND 25;  

输出

当我们执行以上查询时,输出结果如下:

ID NAME AGE ADDRESS SALARY
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

MySQL BETWEEN 与 IN 运算符

BETWEEN 运算符和 IN 运算符可以一起用于 MySQL 查询,以选择在指定范围内且也与指定值匹配的值。

语法

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

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
AND column_name IN (list_of_values);

示例

在此示例中,我们选择薪资在 4000 到 10000 之间的所有客户。此外,我们仅使用 SQL 中的IN 运算符检索居住在 MP 和 Bhopal 的客户。

SELECT * FROM CUSTOMERS 
WHERE SALARY BETWEEN 4000 AND 10000 
AND ADDRESS IN ('Hyderabad', 'Bhopal');

输出

获得以下结果:

ID NAME AGE ADDRESS SALARY
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00

MySQL BETWEEN 与 UPDATE 语句

MySQL 中的 UPDATE 语句用于修改数据库表中的现有数据。在 UPDATE 语句中使用 BETWEEN 运算符以更新指定范围内的值。

示例

让我们使用以下查询更新年龄介于 25 到 30 之间的客户的薪资:

UPDATE CUSTOMERS 
SET SALARY = 10000 
WHERE AGE BETWEEN 20 AND 25;

验证

让我们使用以下查询验证薪资是否已更新:

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 10000.00
3 Kaushik 23 Kota 10000.00
4 Chaitali 25 Mumbai 10000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 10000.00
7 Muffy 24 Indore 10000.00

BETWEEN 运算符与 DELETE 语句

我们还可以在 DELETE 语句中使用 BETWEEN 运算符以删除指定范围内的行。

示例

现在,让我们使用 DELETE 命令删除年龄介于 18 到 20 之间的客户。

DELETE FROM CUSTOMERS 
WHERE AGE BETWEEN 20 AND 22;  

验证

让我们使用以下查询验证指定年龄的员工是否已删除:

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

MySQL NOT BETWEEN 运算符

MySQL 中的NOT BETWEEN 运算符是 BETWEEN 运算符的否定。这用于检索不存在于指定范围或时间间隔内的数据。

语法

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

SELECT column_name(s)
FROM table_name
WHERE column_name NOT BETWEEN value1 AND value2;

示例

考虑 CUSTOMERS 表以检索年龄不在 20 到 25(数值数据)之间的客户的详细信息,使用以下查询。

SELECT * FROM CUSTOMERS 
WHERE AGE NOT BETWEEN 20 AND 25;

输出

以下是输出结果:

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
5 Hardik 27 Bhopal 8500.00

NOT BETWEEN 运算符与 IN 运算符

与 BETWEEN 运算符类似,我们还可以将 NOT BETWEEN 运算符与 IN 运算符结合使用。这是为了选择超出范围且也不与指定值匹配的值。

示例

在以下查询中,我们选择薪资在 1000 到 5000 之间的客户。此外,我们没有使用 SQL 中的IN 运算符检索居住在 Bhopal 的员工。

SELECT * FROM CUSTOMERS 
WHERE SALARY NOT BETWEEN 1000 AND 5000 
AND ADDRESS NOT IN ('Bhopal');

输出

以下是输出结果:

ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00
7 Muffy 24 Indore 10000.00

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

我们还可以使用客户端程序在 MySQL 表上应用 BETWEEN 运算符。

语法

以下是各种编程语言中 MySQL 表中 Between 运算符的语法:

要在 MySQL 中通过 PHP 程序执行 Between 运算符,我们需要使用名为query()mysqli 函数执行带有 BETWEEN 语句的 SQL 查询,如下所示:

$sql = "SELECT column1, column2, ... FROM table_name 
WHERE column_name BETWEEN value1 AND value2";
$mysqli->query($sql);

要在 MySQL 中通过 JavaScript 程序执行 Between 运算符,我们需要使用名为mysql2query()函数执行包含 BETWEEN 语句的 SQL 查询,如下所示:

sql = " SELECT column_name(s) FROM table_name 
WHERE column_name BETWEEN value1 AND value2";
con.query(sql);

要在 MySQL 中通过 Java 程序执行 Between 运算符,我们需要使用名为executeQuery()JDBC 4 类型驱动程序函数执行包含 BETWEEN 语句的 SQL 查询,如下所示:

String sql = "SELECT column1, column2, ... FROM table_name 
WHERE column_name BETWEEN value1 AND value2";
statement.executeQuery(sql);

要在 MySQL 中通过 Java 程序执行 Between 运算符,我们需要使用名为execute()MySQL Connector/Python函数执行包含 BETWEEN 语句的 SQL 查询,如下所示:

between_query = "SELECT column1, column2, ... FROM table_name 
WHERE column_name BETWEEN value1 AND value2"
cursorObj.execute(between_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 SALARY BETWEEN 4000 AND 10000"; $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 5, Name: Hardik, Age: 27, Address Vishakapatnam, Salary 8500.000000
Id 6, Name: Komal, Age: 0, Address Vishakapatnam, Salary 4500.000000
Id 7, Name: Muffy, Age: 24, Address , 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 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 BETWEEN Clause
  sql = "SELECT * FROM employee_tbl WHERE daily_typing_pages BETWEEN 170 AND 300;"
  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
  },
  {
    id: 5,
    name: 'Zara',
    work_date: 2007-06-05T18:30:00.000Z,
    daily_typing_pages: 300
  }
]        
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BetweenClause {
    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";
            rs = st.executeQuery(sql);
            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);
            }
            String sql1 = "UPDATE CUSTOMERS SET SALARY = 10000 WHERE AGE BETWEEN 20 AND 25";
            st.executeUpdate(sql1);
            String sql2 = "SELECT * FROM CUSTOMERS";
            rs = st.executeQuery(sql2);
            System.out.println("Table records after 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 records before update: 
Id: 1, Name: Ramesh, Age: 32, Addresss: Hyderabad, Salary: null
Id: 2, Name: Khilan, Age: 25, Addresss: null, Salary: 10000.00
Id: 3, Name: kaushik, Age: null, Addresss: Hyderabad, Salary: 2000.00
Id: 4, Name: Chaital, Age: 25, Addresss: Mumbai, Salary: 10000.00
Id: 5, Name: Hardik, Age: 27, Addresss: Vishakapatnam, Salary: 8500.00
Id: 6, Name: Komal, Age: null, Addresss: Vishakapatnam, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Addresss: null, Salary: 10000.00
Table records after update: 
Id: 1, Name: Ramesh, Age: 32, Addresss: Hyderabad, Salary: null
Id: 2, Name: Khilan, Age: 25, Addresss: null, Salary: 10000.00
Id: 3, Name: kaushik, Age: null, Addresss: Hyderabad, Salary: 2000.00
Id: 4, Name: Chaital, Age: 25, Addresss: Mumbai, Salary: 10000.00
Id: 5, Name: Hardik, Age: 27, Addresss: Vishakapatnam, Salary: 8500.00
Id: 6, Name: Komal, Age: null, Addresss: Vishakapatnam, Salary: 4500.00
Id: 7, Name: Muffy, Age: 24, Addresss: null, Salary: 10000.0            
import mysql.connector
#establishing the connection
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
cursorObj = connection.cursor()
between_query = f"""
SELECT * FROM CUSTOMERS WHERE SALARY BETWEEN 4000 AND 10000;
"""
cursorObj.execute(between_query)
# Fetching all the rows that meet the criteria
filtered_rows = cursorObj.fetchall()
for row in filtered_rows:
    print(row)
cursorObj.close()
connection.close()                         

输出

以下是上述代码的输出:

(1, 'Ramesh', 32, 'Hyderabad', Decimal('4000.00'))
(2, 'Khilan', 25, 'Kerala', Decimal('8000.00'))
(5, 'Hardik', 27, 'Vishakapatnam', Decimal('10000.00'))
(6, 'Komal', 29, 'Vishakapatnam', Decimal('7000.00'))
(7, 'Muffy', 24, 'Delhi', Decimal('10000.00'))         
广告