=1.select基本查询语句
(1)列的查询
select <列名1>、<列名2>,... from <表名>;
如:从学生表中查询姓名和性别两列
select stu_name,sex from student;

(2)为列设置别名as
sql语句使用as关键字为列设定别名,别名使用中文时需要用双引号括起来,as可省略
select stu_name as "姓名",sex as "性别" from student;
(3) 删除重复数据distinct
select distinct 字段名 from 表名;
select distinct stu_id,stu_name from student;
注:此时只有stu_id和stu_name相同时才会删除
select distinct stu_name from student;

2.指定查询条件
select 字段 from 表名 where 筛选条件
运行顺序:from--where--select
select * from student where stu_name='猴子';

3.注释
单行注释
--查询出全部列
slect * from student;
多行注释
/*
查找姓名是猴子的学生的学号
*/
select stu_id from student where stu_name='猴子';
4.简单运算符
.+号的作用
mysql中的加号只充作运算符两个操作数均为数值型,做加法运算;其中一方为字符型,比如'123'+90,此时会将字符型转换成数值型,若转换成功,继续做加法运算;
若转换失败,则将字符型数值转换为0,与其他进行加法运算。若只要其中一方为NULL,则结果肯定为NULL.
5.逻辑运算符
按逻辑表达式筛选,逻辑表达式主要用于连接条件表达式的
and两个条件均为ture,结果是true;反之则为false;
or只要有一个条件为true,结果为true,反之为false
not 如果连接的条件本身为false,结果为true,反之为false
case:select stu_id from score where not score >=60;(不大于60)
6.模糊查找
like 、 between and、in、is null
(1)like
特点:一般与通配符搭配使用,通配符:%,代表任意多个字符,也包含0个字符;
_下划线,代表单个字符
案例1:查询员工名中包含字符a的员工信息(筛选条件比较模糊,此时命令中的a为字符型,因此要加单引号,此时的百分号表示通配符的作用)
select * from employees where last_name like '%a%';
案例2:查询员工名中第三个字符为c,第五个字符为h的员工名
select last_name,salary from employees where last_name like '__c__h%';
#案例3:查询员工中第二个字符为_的员工名(此时下划线充当字符,可以通过转译的方式)
select last_name from employees where last_name like '_$_%'escape'$';
(2)between and
注意事项:使用between and 可以提高语句的简洁度
包含连接值(即区间端点值)
等价于大于等于左边的值小于等于右边的值
#案例1:查询员工编号在100到120之间的所有的员工信息
select * from employees where employee_id between 100 and 120;
(3)in
注意:含义是指用于判断某字段的值是否属于in列表中的某一项
特点:使用in做筛选比使用or提高语句简洁度
in列表的值类型必须统一或者是兼容
in列表中的字段不支持使用通配符或者下划线等类似于like的通配符
案例1:查询员工的公众编号是it_prog、ad_vp、ad_pres中的一个的员工名和工种编号
select last_name,job_id from employees where job_id IN('it_prog','ad_vp','ad_pres');
(4)is null的使用(要使用is null而非= null)
注意:等号或者不等于号不能用于判断null值,is null或者is not null 可以判断null值;
#案例1:查询没有奖金的员工名和奖金率
select last_name,commission_pct from employees where commission_pct is null;
select last_name,commission_pct from employees where commission_pct is not null;
(5)安全等于<=> 含义是判断是否等于
也可以用于判断null值,还可以用来判断普通类型的值
案例:查询工资为12000的员工信息但是可读性很差
select * from employees where salary <=> 12000;
select last_name,commission_pct from employees where commission_pct <=> null;
比较is null 和<=>
is null 仅仅用于判断null值,而<=>既可以判断Null值又可以判断普通数值
is null可读性较高,而<=>可读性较低,建议使用 is null
对于查询的字段可能出现空值时:
#2.查询员工号为176的员工的姓名、部门号、年薪(因为奖金率会存在空值)
select last_name,department_id,salary*12*(1+ifnull(commission_pct,0)) as 年薪 from employees where department_id =100;
练习:



