主键约束(自带唯一约束): create database yueshu character set utf8; use yueshu; show tables; create table tbl_PK( id int unsigned(无符号) primary key auto_increment(自动增长),(顺序不能错) name varchar(30)); insert tbl_PK values(1,'张三'),(2,'李四'),(3,'王五'); select * from tbl_PK; insert tbl_PK values(0,'张三'),(0,'李四'),(0,'王五');
唯一约束: create table tbl_UQ( id int unsigned primary key auto_increment, card_id varchar(18) unique); insert into tbl_UQ values(0,'123123'); select * from tbl_UQ; insert into tbl_UQ values(0,'123123'); insert into tbl_UQ values(0,'123123321'); select * from tbl_UQ;
非空约束: create table tbl_NN( id int unsigned primary key auto_increment, name varchar(10) not null); alter table tbl_NN add age int unsigned; desc tbl_NN; insert into tbl_NN values(0, '张三'); insert into tbl_NN(id,name) values(0, '张三'); select * from tbl_NN; insert into tbl_NN(id,age) values(0, 18);
默认约束: create table tbl_Default( id int unsigned primary key auto_increment, gender char(2) not null default '男'); alter table tbl_Default add name varchar(30); insert into tbl_Default(id, name) values(0,'张三'); select * from tbl_Default;
检查约束:(MySQL中不起作用) create table tbl_Check( id int, age int check ( age > 0 and age < 120), gender char(2) check ('男' or '女')); insert into tbl_Check values(0, 180, '中性'); select * from tbl_Check;
alter table Employees add constraint FK_DeptId_DepId foreign key(DeptId) references Department(DepId); 外键必须和主键关联 insert into Department values(0,'一部门'),(0,'二部门'); select * from Department; insert into Employees(EmpId,DeptId) values(0,1); select * from Employees; insert into Employees(EmpId,DeptId) values(0,3); drop table Department; drop table Employees; drop table Department;
聚合函数(聚合函数不计算null值) - 对多条数据进行统计
把某字段中的数据分组 select 字段名字1 from 表的名字 group by 字段名字1;
根据某字段(字段名字1)分组,显示其它字段(字段名字2)成分 select 字段名字1,group_concat(字段名字2) from 表的名字 group by 字段名字1;
求和 select sum(字段名字) as '别名' from 表的名字;
求最大 select max(字段名字) as '别名' from 表的名字;
求最小 select min(字段名字) as '别名' from 表的名字;
求平均 select avg(字段名字) as '别名' from 表的名字;
求某字段所含数据的总个数(不算null那一行) select count(字段名字) as '别名' from 表的名字;
分组之后显示每组的数据个数 select 字段名字1,count(*) from 表的名字 group by 字段名字1;
保留小数指定位数 select round(那个小数,保留的位数) from 表的名字;
having 对分组之后的数据进行进一步的筛选 类似于 select 和 where 之间的关系 select 字段名字1 from 表的名字 group by 字段名字1 having 条件;
多表查询 - 尽量避免多表查询 - 多表查询会出现笛卡尔积
内连接,满足条件显示(还是会产生笛卡尔积,只是用on进行了条件筛选) select * from 表1的名字 inner join 表2的名字 on 表1的名字.字段的名字 = 表2的名字.字段的名字;
左连接,以表1为基础,表1全显示,表2不够的用null补全 select * from 表1的名字 left join 表2的名字 on 表1的名字.字段的名字 = 表2的名字.字段的名字;
右连接,以表2为基础,表2全显示,表1不够的用null补全 select * from 表1的名字 right join 表2的名字 on 表1的名字.字段的名字 = 表2的名字.字段的名字;
自关联 - 让表自己和自己进行连接 - 表中的某一列关联了表中的另外一列,但是他们的业务含义是不一样的 select * from 表的名字 inner join 表的名字 on 表的名字.字段的名字 = 表的名字.字段的名字; 代码示例: Create table areas ( id int, atitle varchar(100), pid int )
如: id 编号 pid 上级编号
id atitle pid 1 河北省 null 2 石家庄 1 3 平山县 2
子查询 select * from 表1的名字 where 字段1的名字=(select 字段2的名字 from 表2的名字 where 条件)
执行顺序: 1—from 表名 2—where 3—group by 4—select distinct * 5—having 6—order by 7—limit
网友评论