having子句
用来对多行函数结果进行过滤
- having 和 where 作用相同,都是条件过滤 where 过滤普通条件,最早执行 having
过滤多行函数结果,分组,求完多行函数后,才执行 having 跟在 group by 后面
只有一个手下的主管id
select mgr_id, count(*) c
from emps
where mgr_id is not null
group by mgr_id
having c=1;
平均工资小于等于5000的岗位代码
select job_id, avg(sal) a
from emps
group by job_id
having a<=5000;
条件子查询
一个查询的查询结果,作为另一个查询的过滤条
select .. where a=(select ...)
工资小于平均工资
select avg(sal) from emps;
select id,fname,sal
from emps
where sal<6461.682243;
select id,fname,sal
from emps
where sal<(
select avg(sal) from emps
);
约束
限制字段中的取值
主键
外键
非空
唯一
检查
主键
数据表中,一行数据的唯一标识
不重复
不能是null值
自动生成索引
一般使用“非业务数据”来作为主键
自动增加
随机生成
自增主键
整数类型主键,可以设置自动生成自增的值
create table xuesheng (
id int primary key auto_increment,
....
);
– 修改表,把主键id修改成自增
alter table xuesheng
modify id int auto_increment;
获得刚刚产生的自增值
last_insert_id()
只获得当前会话产生的自增值
select last_insert_id();
外连接
内连接
只查询满足连接条件的数据
外连接
不满足连接条件的数据也要查询
左外连接
查询左侧表条件外数据
右外连接
查询右侧表条件外数据
全外连接
双侧表条件外数据
MySql不支持
标准的表连接语法
select ...
from a join b
on(a.id=b.xid)
join c
on(...)
select ...
from a left join b
on(a.id=b.xid)
select ...
from a right join b
on(a.id=b.xid)