1.简单查询
1.1语法
select 列名1 别名1,列名2 别名2,... from 表名
1.2用法
emp表结构如下图:
- 查询员工信息
select ename from emp; -- 查询员工姓名
select ename,empnp from emp; -- 查询员工姓名、编号
- 查询员工所有信息
select * from emp;
- 查询员工信息,并为每列设置别名
select ename 姓名,sal 工资 from emp;
Windows的DOS窗口可能会报错,因为DOS默认使用gbk,不支持中文,执行下列指令解决
set names gbk;
- 查询员工年薪
select ename,(sal+comm)*12 from emp; --NULL参与任何运算时,结果都为NULL
使用ifnull(a,b)函数,如果a不为null,返回a,否则返回b。
select ename,(sal+ifnull(comm,0)*12) from emp; -- 将null变为0,参与运算
- 去除重复
使用distinct去除重复行,写在列名前。
select distinct job from emp; -- 查找emp表中不同的job类型
2.限定查询
语法:在简单查询语句的后面加where条件。
select 列名1 别名1,列名2 别名2,... from 表名 where 条件;
2.1比较运算符
>、<、>=、<=、=、!=
select ename from emp where sal>1500; -- 查询工资大于1500的雇员姓名
对于自己写的字符串,需要使用引号。
select empno from emp where ename='smith'; -- 查询名字是smith的员工编号
2.2null和not null
- 查询每月没有奖金的员工信息
不能使用where comm=null判断某字段是否为null,需要使用is或is not。
select * from emp where comm is null;
2.3其他条件语句
- 查询基本工资大于1500,同时可以获得奖金的员工姓名、工资、奖金
select ename,sal,comm from emp where sal>1500 and comm is not null; -- and的用法
- 查询从事销售工作,或工资大于等于2000的员工信息
select * from emp where job='salesman' or sal>=2000; -- or的用法
- 查询从事销售工作,并且工资小于1500以外的员工信息(not的用法)
select * from emp where not (job='salesman' and sale<1500);
- 查询基本工资大于1500,但小于3000的员工信息(between and的用法)
select * from emp where sal>1500 and sal<3000;
select * from emp where between 1500 and 3000; -- 包含1500和3000边界值
select * from emp where hiredate between '1981-1-1' and '1981-12-30'; -- 入职年份在1981年的员工信息
select * from emp where empno in (7788,7499,7369);
3.模糊查询
模糊查询需要结合通配符一起使用。
常用的通配符:
例:
select * from emp where ename like 's%';
select * from emp where ename like '%m%';
select * from emp where ename like '____D'; -- D前面包含4个下划线