sql
and
or
提示
Hive SQL 教程 编写中,本教程可以做为通用 SQL 的学习教程,用来学习 Spark SQL、Impala SQL、Presto,PostgreSQL、MySQL、Oracle、Microsoft SQL Server、SQLite 等数据存储的 SQL 用法。使用过程中有任何建议,提供意见、建议、纠错、催更加微信 sinbam。
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》 已由机械工业出版社出版上市,各大电商平台有售,欢迎关注。
SQL 中的 WHERE 子句中较为复杂的逻辑需要用 AND,OR 和 NOT 运算符结合起来使用,这些逻辑连接符也可以用在其他需要逻辑运算的地方。
本文例子中使用的数据是筛选指定字段中的数据内容。
符号 | 逻辑 | 举例 |
---|---|---|
AND | 和,全部为真 | b_year > 2000 and math > 80 |
OR | 或,只要一个为真 | b_year = 2010 or chinese > 80 |
NOT | 非,与逻辑值相反 | not gender == '男' |
基本使用:
-- 数学大于80的男生
select name, gender, math
from students
where gender = '男'
and math > 80
-- 所在成绩都及格的
select name, gender, math
from students
where math >= 60
and chinese >= 60
and english >= 60
-- 数学或者语文90分及以上的
select name, gender, math
from students
where math >= 90
or chinese >= 90
-- 不是男生
select name, gender
from students
where not gender == '男'
综合使用:
-- 数学或者语文90分及以上,一班的
select name, class, math, chinese
from students
where (math >= 90
or chinese >= 90)
and class = 1
-- 以上基础上再排除男生
select name, gender, class, math, chinese
from students
where (math >= 90
or chinese >= 90)
and class = 1
and not gender == '男'
另外还可以用在 CASE 语句,IF 等函数中。