一、取别名
select xxx as “aaa”
取别名为aaa
二、去重
select DISTINCT xxx
三、多字段拼接为一个字段
select CONCAT('dname',',','id',IFNULL(pact,0)) AS output from xxx
NULL与任何字符拼接均为NULL,因此需要去NULL
其中,IFNULL为判断字段pact是否为空,若为空则为0
四、where子句
select * from employees
where [not] condition1 [and][or] condition2
五、模糊查询
%代表任意0-多个字符
_代表任意单个字符
- like
查询包含a的字段
select name from employees
where lastname like '%a%'
like后面必须加单引号
- between and
select ....
where money between 100 and 200;
- in
select ...
where job_name in('IT','AR','PX' );
等同于job_name=IT or job_name=AR...
- is null|is not null
=无法判断NULL,因此使用这个
六、分组查询
image.png
大表拆分成小表,分别统计
统计该公司不同部门的人数大于2的平均工资
select count(*)....
where ...
group by department_id,job_id
having count(*)>2;
想对聚合函数结果进行约束,即使用having而非where
七、连接查询(多表查询)
select a,b from A ,B
A表10条,B表4条
若直接从AB两表查询,则获得为笛卡尔积40条数据
92语法
连接分为:
内连接:
等值
非等值
自连接
外连接
左
右
内连接
等值
select a,b from A,B
where A.xx=B.xx
非等值
即为将上方等号替换为其他符号
99语法
内连接
/*select 查询列表
from 表1 别名
inner join 表2 别名
on 连接条件
where 筛选调教*/
//查询部门下拥有e名字的员工数大于三个的部门的部门名和员工数量
select name from employees e
inner join departments d
on e.department_id=d.department_id
where e.name likes '%e%'
group by department_id
having count(*)>3;
//三表连接
select name,department_name,job_title
from employees
inner join departments on xxxx
inner join job on xxx
外连接
左外,右外,LFET RIGHT OUTER JOIN
交叉连接(笛卡尔积)
CROSS JOIN
八、子查询
若子查询结果为单行单列用>=<等符号
若为多行单列,用IN,ALL,ANY








网友评论