非空约束
Not null
唯一约束
Unique
主键约束
Primary
默认约束
Default
检查约束
Check
外键约束
Foreign key
Auto -increment
添加外键
Alter table (表名) constraint 外键名称 foreign key(外键字段名) references 主表(主表列名)
删除外键
Alter table 表名 drop foreign key 外键名称
Eg:
Alter table emp add constraint fk_em_dept_id foreign key(dept_id ) references dept(id);
Alter table emp drop foreign key fk_em_dept_id
Alter table emp add contraint fk_em_dept_id foreign key(dept_id) references dept(id) on update cascade on delete cascade;
Alter table emp add contraint fk_em_dept_id foreign key(dept_id) references dept(id) on update cascade on delete cascade;
多表查询:
Select * from emp ,dept;
笛卡尔积
查询的结果为所有组合的情况
消除无效的笛卡尔积
Select * from emp,dept where emp.dept_id =dept.id;
内连接:
查询两张表交集的部分
(隐式内连接)
Select 字段链表 from 表1表2 where 条件.....
(显式内连接)
Select 字段列表 from 表1 [inner] join 表2 on 连接条件
- 隐式内连接
连接条件emp.dept_id =dept.id;
Select emp.name,dept,name from emp , dept where emp.dept_id=dept.id;
2、显示内连接
Select e.name ,d.name from emp e inner join dept d on e.dept_id=d.id;
外连接
左外连接(特点:左外连接左表内容完全被保存,右外连接右表内容被完全保存 )
Select * from 表1 left join 表2 on条件
有外连接
Select * from 表1 right join 表2 on条件
自连接
自连接查询语法
Select 字段列表 from 表A 别名A join 表A 别名B ON 条件
自连接查询可以是内连接查询也可以是外连接查询
Select a.name,b.name from emp a ,emp b where a.managerid=b.id;
联合查询
-union -union all
Select * from emp where salary<5000
Union all
Select * from emp age>50;
去掉重复记录把all去掉
(上下字段类型保持一样)
子查询
Select * from t1 where column1(select column1 from t2);
1、标量字查询
字符串返回的结果是单个值(数字、字符串、日期等) ,最简单的形式,这种字查询被称为标量字查询;
常用的操作符:= <> > >= < <=;
Select *from where dept_id=(Select id from dept where name =‘销售部’)
Select * from emp where entrydate > (select entrydate from emp where name=’方东白’);
2、列子查询
子查询查询的结果是一列或者多行,这种子查询被称为列子查询
常用的操作符为IN、NOT IN、any、some、all
Select * from emp where dept_id in(select id from dept where name=’销售部’or name=‘市场部’);
Select * from emp where salary >all(select salary from emp where dept_id =(select id from dept where name=’财务部’));
3、行子查询
自查询返回的式一行或者多列
Select * from emp where (salary,managerid)=(select salary,managerid from emp where name=’张无忌’);
4、表子查询
子查询返回的结果是多行多列,这种查询被称为表子查询
常见的操作符为IN
Select * from emp where (job,salary) in (select job,salary from emp where name =’鹿杖客’or name=‘宋远桥’);
事务的四大特性
原子性:全部成功或者全部失败
一致性: 事务完成时,必须使所有的数据保持 一致性;
隔离性:数据库提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行
持久性:事务一旦被提交,他对数据库的改变是永久的
并发事务引发的问题
脏读:
不可重复读:
幻读: