MySQL IN 子句

黑派客     最近更新时间:2020-08-04 05:37:59

531

可以使用 IN 子句代替许多 OR 条件。

要想理解 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子句 来完成:

展开阅读全文