MySQL IN 语句的 基本用途是 将一列与多个值进行比较。MySQL IN 语句还有一些高级用法,它们构成了有趣的用例。考虑示例表 user_table ,其中 5 个用户被分配了不同的权限,如管理员、超级用户等,基于值 1 或 0,
mysql> SELECT * FROM user_table;
+-----------+---------+--------------+----------+ ------------+
| 用户 ID | is_admin | is_superuser | is_staff | is_active |
+-----------+---------+--------------+----------+ ------------+
| 1 | 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 |
| 3 | 0 | 1 | 1 | 1 |
| 4 | 0 | 0 | 0 | 1 |
| 5 | 0 | 0 | 0 | 0 |
+-----------+---------+--------------+----------+ ------------+
用例 1:MySQL IN 语句将一个值与多个列进行比较
它的语法是:
SELECT * FROM TableName WHERE value IN (column1, column2, column3, column4)
例如,
mysql> SELECT * FROM user_table WHERE 1 IN (is_admin, is_superuser, is_staff, is_active);
?
+-----------+---------+--------------+----------+ ------------+
| 用户 ID | is_admin | is_superuser | is_staff | is_active |
+-----------+---------+--------------+----------+ ------------+
| 1 | 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 |
| 3 | 0 | 1 | 1 | 1 |
| 4 | 0 | 0 | 0 | 1 |
+-----------+---------+--------------+----------+ ------------+
通常的 IN 语句只涉及 与多个值 进行 比较的一列。
SELECT * FROM TableName WHERE column1 IN (1,2,3,4)
它作为
SELECT * FROM TableName WHERE column1 = 1 OR column1 = 2 OR column1 = 3 OR column1 = 4
此语句是 与 多个列进行比较的 VALUE
SELECT * FROM TableName WHERE 1 IN (column1, column2, column3, column4)
和
SELECT * FROM TableName WHERE column1 = 1 OR column2 = 1 OR column3 = 1 OR column4 = 1
用例 2:MySQL IN 语句比较多列和多个值
它的语法是:
SELECT * FROM TableName WHERE (column1,column2) in ((value1,value2),(value3,value4),..)
例如,
mysql> SELECT * FROM user_table WHERE (is_staff,is_admin) in ((1,0),(1,1));
+-----------+---------+--------------+----------+ ------------+
| 用户 ID | is_admin | is_superuser | is_staff | is_active |
+-----------+---------+--------------+----------+ ------------+
| 1 | 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 |
+-----------+---------+--------------+----------+ ------------+
它作为
SELECT * FROM user_table WHERE (is_staff=1 and is_admin=0) or (is_staff=1 and is_admin=1);
|