SQL AND & OR 运算符

SQL AND & OR 运算符 #

AND & OR 运算符用于基于一个以上的条件对记录进行过滤。

如果第一个条件和第二个条件都成立,则 AND 运算符显示一条记录。

如果第一个条件和第二个条件中只要有一个成立,则 OR 运算符显示一条记录。

AND 运算符实例 #

下面的 SQL 语句从 “domains” 表中选取icp为 “west.cn” 且id大于 “30” 的所有记录:

实例

MariaDB [learnsql]> select * from domains where icp='west.cn' and id>30;
+----+---------+------------------+------------+------------+
| ID | ICP     | DomainName       | RegDate    | EndDate    |
+----+---------+------------------+------------+------------+
| 31 | west.cn | smdm.top         | 2018/9/10  | 2028/9/10  |
| 32 | west.cn | commandline.top  | 2020/10/21 | 2029/10/21 |
| 33 | west.cn | wxtx.top         | 2020/8/11  | 2030/8/11  |
| 34 | west.cn | kjzx.top         | 2020/8/16  | 2030/8/16  |
| 35 | west.cn | aido.cc          | 2020/9/22  | 2030/9/22  |
| 36 | west.cn | ustv.top         | 2020/10/13 | 2030/10/13 |
| 37 | west.cn | colorhexcode.top | 2021/1/27  | 2031/1/27  |
| 38 | west.cn | rgbs.top         | 2021/2/25  | 2031/2/25  |
| 39 | west.cn | autohotkey.top   | 2021/3/3   | 2031/3/3   |
| 40 | west.cn | opensuse.top     | 2021/3/25  | 2031/3/25  |
| 41 | west.cn | qgis.top         | 2021/8/23  | 2031/8/23  |
| 42 | west.cn | hugotheme.top    | 2022/2/18  | 2032/2/18  |
| 51 | west.cn | guwendaquan.cn   | 2022/6/9   | 2023/6/9   |
+----+---------+------------------+------------+------------+
13 rows in set (0.000 sec)

OR 运算符实例 #

下面的 SQL 语句从 “domains” 表中选取icp为 “google” 或者 “wanwang” 的所有记录:

MariaDB [learnsql]> select * from domains where icp='google' or icp='wanwang';
+----+---------+-------------+------------+------------+
| ID | ICP     | DomainName  | RegDate    | EndDate    |
+----+---------+-------------+------------+------------+
|  6 | wanwang | dotbbq.com  | 2017/10/28 | 2022/10/28 |
|  7 | wanwang | lyq.wiki    | 2018/12/27 | 2022/12/28 |
| 17 | wanwang | linuxuc.com | 2016/3/24  | 2023/3/24  |
| 19 | wanwang | unixetc.com | 2017/3/30  | 2023/3/30  |
| 22 | google  | suopo.net   | 2020/6/17  | 2023/6/17  |
+----+---------+-------------+------------+------------+
5 rows in set (0.001 sec)

结合 AND & OR #

您也可以把 AND 和 OR 结合起来(使用圆括号来组成复杂的表达式)。

下面的 SQL 语句从 “domains” 表中选取id大于 “10” 且icp为 “google” 或 “wanwang” 的所有记录:

MariaDB [learnsql]> select * from domains where id>10 and (icp='google' or icp='wanwang');
+----+---------+-------------+-----------+-----------+
| ID | ICP     | DomainName  | RegDate   | EndDate   |
+----+---------+-------------+-----------+-----------+
| 17 | wanwang | linuxuc.com | 2016/3/24 | 2023/3/24 |
| 19 | wanwang | unixetc.com | 2017/3/30 | 2023/3/30 |
| 22 | google  | suopo.net   | 2020/6/17 | 2023/6/17 |
+----+---------+-------------+-----------+-----------+
3 rows in set (0.001 sec)