优先顺序(优先级从左至右)
- 小括号,not,比较运算符,逻辑运算符
- and比or先运算,如果同时出现并希望先算or,需要结()使用
查询的基本语法
select * from 表名;
- from关键字后面写表名,表示数据来源于是这张表
- select后面写表中的列名,如果是*表示在结果中显示表中所有列
- 在select后面的列名部分,可以使用as为列起别名,这个别名出现在结果集中
- 如果要查询多个列,之间使用逗号分隔
消除重复行
在select后面列前使用distinct可以消除重复的行
select distinct gender from student;
条件
- 使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
语法如下:
select * from 表名 where 条件
比较运算符
= > >= < <= <> !=
select * from student where id>3
逻辑运算符
and or not
- 查询编号大于3的女同学
select * from student where id>3 and gender=0;
- 查询编号小于4或者没有被删除的学生
select * from student where id<4 or isdelete=0;
模糊查询
- like
- %表示任意多个字符
- _表示一个任意字符
查询姓刘的学生
select * from student where name like '黄%'
查询姓黄并且名字是一个字的学生
select * from student where name like '黄_'
查询姓黄或者姓刘的学生
select * from student where name like '黄%' or name like '刘%'
查询范围
- in 表示在一个非连续的范围内
- between … and … 表示在一个连续的范围内
查询编号是1或3或8的学生
select * from student where id in(1,3,8);
查询学生编号是3至8的学生
select * from student where id between 3 and 8;
查询学生是1至5的男生
select * from student where id between 1 and 5 and gender=1;
注意:如果逻辑语中的and和范围查询中的and同时有时,记住:从左往右,发现between开始,往右的第一个and与between组成范围查询,其余的and才是逻辑语。
空判断
- null与’'是不同的
- 判空is null
- 判非空 is not null
查询没有填写地址的学生
select * from student where hometown is null;
查询有填写地址的学生
select * from student where hometown is not null;
查询填写了地址的女生
select * from student where hometown is not null and gender=0;
注:
null是真正的空的,不占内存,故不能用=对其进行判断;只能采用is null 或者 is not null 进行判断
''是空字符串,占用内存的