Home Database Mysql Tutorial MySQL的WHERE语句中BETWEEN与IN的使用教程_MySQL

MySQL的WHERE语句中BETWEEN与IN的使用教程_MySQL

May 27, 2016 pm 01:46 PM


MySQL BETWEEN 用法

MySQL BETWEEN 语法

BETWEEN 运算符用于 WHERE 表达式中,选取介于两个值之间的数据范围。BETWEEN 同 AND 一起搭配使用,语法如下:

WHERE column BETWEEN value1 AND value2
WHERE column NOT BETWEEN value1 AND value2
Copy after login

通常 value1 应该小于 value2。当 BETWEEN 前面加上 NOT 运算符时,表示与 BETWEEN 相反的意思,即选取这个范围之外的值。

相关mysql视频教程推荐:《mysql教程

BETWEEN 实例

选取 uid 在 2 到 5 之间的用户数据:

SELECT * FROM user WHERE uid BETWEEN 2 AND 5
Copy after login

返回查询结果如下:

20151216160201795.png (639×132)

除了数值类型外,BETWEEN 也支持字符串范围,如下选择出所有 username 介于 a 至 j 之间的用户(并包括单字母k/K):

SELECT * FROM user WHERE username BETWEEN 'a' AND 'k'
Copy after login

字符范围也支持汉字,但通常来说没什么意义。

MySQL BETWEEN 边界

虽然几乎所有的数据库都支持 BETWEEN ... AND 运算符,但不同的数据库对 BETWEEN ... AND 处理方式是有差异的。在 MySQL 中,BETWEEN 包含了 value1 和 value2 边界值,如上面选取 uid 在 2 到 5 之间的用户数据例子。
而有的数据库则不包含 value1 和 value2 边界值(类似于 > and

// int 时间戳格式,查询 2008-08-08 20:00:00 到 2009-01-01 零点之前的数据
SELECT * FROM table WHERE column_time BETWEEN 1218196800 AND 1230739199

// DATE 格式,查询 2008-08-08 到 2009-01-01 零点之前的数据
SELECT * FROM table WHERE column_time BETWEEN '2008-08-08' AND '2009-01-01'

// DATETIME 格式,查询 2008-08-08 20:00:00 到 2009-01-01 零点之前的数据
SELECT * FROM table WHERE column_time BETWEEN '2008-08-08 20:00:00' AND '2008-12-31 23:59:59'
但对于查询到当前时间的数据,建议使用 >= 运算符:
// DATETIME 格式,查询 2008-08-08 20:00:00 到当前时刻的数据
SELECT * FROM table WHERE column_time >= '2008-08-08 20:00:00'
Copy after login

可见,同样的需求,不同的字段类型,写法可能就不一样。从效率上来讲,int 时间戳格式效率最优。
以上 BETWEEN 的各个例子,虽然都是 SELECT 查询,但 BETWEEN 也可以用于 UPDATE、DELETE 等适用 WHERE 表达式的 SQL 中。
MySQL BETWEEN 数据比较

BETWEEN 还具有数据比较功能,语法如下:

expr BETWEEN min AND max
Copy after login

当 expr 表达式的值大于或等于 min 且小于或等于 max 时, BETWEEN 的返回值为 1 ,否则返回 0 。利用这个功能,可以判断一个表达式或值否则在某个区间:

// 返回 0
SELECT 1 BETWEEN 2 AND 3
// 返回 1
SELECT 'b' BETWEEN 'a' AND 'c'
// 判断日期范围
SELECT 20080808 BETWEEN 20080101 AND 20090101
Copy after login

BETWEEN 与 <、

MySQL IN 用法
MySQL IN 语法
IN 运算符用于 WHERE 表达式中,以列表项的形式支持多个选择,语法如下:

WHERE column IN (value1,value2,...)
WHERE column NOT IN (value1,value2,...)
Copy after login

当 IN 前面加上 NOT 运算符时,表示与 IN 相反的意思,即不在这些列表项内选择。
IN 使用实例

选取 uid 为 2、3、5 的用户数据:

SELECT * FROM user WHERE uid IN (2,3,5)
Copy after login

返回查询结果如下:

20151216160410446.png (638×104)

IN 子查询

更多情况下,IN 列表项的值是不明确的,而可能是通过一个子查询得到的:
SELECT * FROM article WHERE uid IN(SELECT uid FROM user WHERE status=0)
在这个 SQL 例子里,我们实现了查出所有状态为 0 的用户(可能是被禁止)的所有文章。首先通过一个查询得到所有所有 status=0 的用户:

SELECT uid FROM user WHERE status=0
Copy after login

然后将查询结果作为 IN 的列表项以实现最终的查询结果,注意在子查询中返回的结果必须是一个字段列表项。
IN 运算符补充说明

IN 列表项不仅支持数字,也支持字符甚至时间日期类型等,并且可以将这些不同类型的数据项混合排列而无须跟 column 的类型保持一致:

SELECT * FROM user WHERE uid IN(1,2,&#39;3&#39;,&#39;c&#39;)
Copy after login

一个 IN 只能对一个字段进行范围比对,如果要指定更多字段,可以使用 AND 或 OR 逻辑运算符:
SELECT * FROM user WHERE uid IN(1,2) OR username IN('admin','5idev')
使用 AND 或 OR 逻辑运算符后,IN 还可以和其他如 LIKE、>=、= 等运算符一起使用。
关于 IN 运算符的效率问题

如果 IN 的列表项是确定的,那么可以用多个 OR 来代替:

SELECT * FROM user WHERE uid IN (2,3,5)
// 等效为:
SELECT * FROM user WHERE (uid=2 OR aid=3 OR aid=5)
Copy after login

一般认为,如果是对索引字段进行操作,使用 OR 效率高于 IN,但对于列表项不确定的时候(如需要子查询得到结果),就必须使用 IN 运算符。另外,对于子查询表数据小于主查询的时候,也是适用 IN 运算符的。

以上就是MySQL的WHERE语句中BETWEEN与IN的使用教程_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles