扫码一下
查看教程更方便
MySQL IN 子句是用来判断要检索的字段的值是否在给定的数组中,它可以替换OR条件。
SELECT column_name, function(column_name)
FROM table_name
WHERE column_name IN (value1,value2,....)
要理解IN子句,先来看下面的例子。有一个employee_tbl表,该表具有以下记录
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 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 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
现在,假设基于上表您想要显示 Daily_typing_pages 等于 250、220 和 170 的记录。这可以使用OR条件完成,如下所示
mysql>SELECT * FROM employee_tbl
->WHERE daily_typing_pages= 250 OR
->daily_typing_pages= 220 OR daily_typing_pages= 170;
结果如下:
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 4 | Jill | 2007-04-06 | 220 |
+------+------+------------+--------------------+
4 rows in set (0.02 sec)
同样可以使用IN子句实现如下
mysql> SELECT * FROM employee_tbl
-> WHERE daily_typing_pages IN ( 250, 220, 170 );
结果如下:
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 4 | Jill | 2007-04-06 | 220 |
+------+------+------------+--------------------+
4 rows in set (0.02 sec)