16. SQL--and和or运算符
1. 前言
sql 中的 and 和 or 运算符用来连接多个查询条件,以缩小返回的结果集,它们被称为连接符。
and 运算符
and 运算符用于连接 where 子句中的多个查询条件,只有当这些查询条件都被满足时,数据行(记录)才会被选取。
语法
where 子句中 and 运算符的基本语法如下:
select column1, column2, columnn
from table_name
where [condition1] and [condition2]...and [conditionn];
您可以使用 AND 运算符连接 N 个条件,只有当这些条件都被满足时,SQL 语句才会奏效。
示例
例如有如下的 website 表:
+----+----------------+----------------------------+-----+-------+---------+---------+ | id | name | url | age | alexa | uv | country | +----+----------------+----------------------------+-----+-------+---------+---------+ | 1 | 百度 | https://www.baidu.com/ | 21 | 4 | 5010.5 | CN | | 2 | 淘宝 | https://www.taobao.com/ | 17 | 8 | 3996.75 | CN | | 3 | C语言中文网 | http://c.biancheng.net/ | 12 | 7923 | 11.62 | CN | | 4 | Google | https://www.google.com/ | 23 | 1 | 36474 | US | | 5 | GitHub | https://github.com/ | 13 | 95 | 216.3 | US | | 6 | Stack Overflow | https://stackoverflow.com/ | 16 | 48 | 592.2 | US | | 7 | Yandex | http://www.yandex.ru/ | 11 | 53 | 591.82 | RU | | 8 | VK | https://vk.com/ | 23 | 23 | 1206 | RU | +----+----------------+----------------------------+-----+-------+---------+---------+
下面的代码,将从 website 表中选取出 id、name、url 和 uv 四个字段,并且满足日访问量(uv)大于 500 万、年龄(age)小于 20 两个条件:
select id, name, url, uv
from website
where uv>500 and age<20;
执行结果如下:
+----+----------------+----------------------------+---------+
| id | name | url | uv |
+----+----------------+----------------------------+---------+
| 2 | 淘宝 | https://www.taobao.com/ | 3996.75 |
| 6 | Stack Overflow | https://stackoverflow.com/ | 592.2 |
| 7 | Yandex | http://www.yandex.ru/ | 591.82 |
+----+----------------+----------------------------+---------+
2. or 运算符
or 运算符用于连接 where 子句中的多个查询条件,只要满足其中一个条件,数据行(记录)就能被选取。
语法
where 子句中 or 运算符的基本语法如下:
select column1, column2, columnn
from table_name
where [condition1] or [condition2]...or [conditionn]
您可以使用 or 运算符连接 n 个条件,只要满足其中一个条件,sql 语句就奏效。
示例
仍然使用上面的 website 表,从 customers 表中选取出 id、name、url 和 uv 四个字段,并且日访问量(uv)小于 500 万,或者年龄(age)大于 20:
select id, name, url, uv
from website
where uv<500 or age>20;
执行结果如下:
+----+-------------+-------------------------+--------+
| id | name | url | uv |
+----+-------------+-------------------------+--------+
| 1 | 百度 | https://www.baidu.com/ | 5010.5 |
| 3 | C语言中文网 | http://c.biancheng.net/ | 11.62 |
| 4 | Google | https://www.google.com/ | 36474 |
| 5 | GitHub | https://github.com/ | 216.3 |
| 8 | VK | https://vk.com/ | 1206 |
+----+-------------+-------------------------+--------+
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)