当前位置: 代码迷 >> 综合 >> MySQL建表的一些约束条件
  详细解决方案

MySQL建表的一些约束条件

热度:88   发布时间:2024-01-25 18:17:22.0

1.SQL :结构化查询语言(Structer Query Language)

  包含DDL,DCL ,DML,TCL四种语句

  DDL:create / alter / dropDCL: grant / revokeDML: select / update / insert / deleteTCL:rollback / commit /  savepoint

2.SQL 建表的约束条件

create table book(`id` int not null primary key auto_increment,`bookname` varchar(20),`price` float);

 

1.主键约束

唯一性,不能为空 ,MySQL中可以通过设置为自动增长的整数

`id` int not null primary key auto_increment

2.非空约束

   not nullalter table book modify `price` float not null;

 

3.默认值

alter table book modify `price` float not null default 0;

 

4.唯一性约束

unique   唯一性

alter table book modify `bookname` varchar(20) unique;

 

5.索引约束

主键是一个唯一性索引,创建唯一性索引

alter table book add unique index(`bookname`);

 

   创建普通索引

alter table book add index(`price`);

 

   删除索引

alter table book  drop index `bookname` ;

什么时候需要索引?

 

6.外键约束

create table `class`(id int not null primary key auto_increment,className varchar(20) not null)
create table student(id int not null primary key auto_increment,stuName varchar(20),sex char(2),cid int,constraint fk_1 foreign key(cid) references `class`(id))

 

测试:

insert into student(stuName,sex,cid) values('zhangsan','m',1);

3.三大范式

     创建数据库表时候的规范

 

   第一范式[1NF]

    原子性:所有的字段都具有原子性,是不可再拆分的,违反第一范式,就需要将该字段继续拆分成多个字段

   users表

id  uname    upwd  m-tel       tel1   zhangsan 1234  13812345678 0731-12345678

 

  第二范式[2NF]

 主键依赖:  先满足1NF,每个字段都必须依赖于主键存在

用户买了一本书,书本和用户没有依赖关系,书本名称book就不能作为users表的字段

违反第二范式,需要创建另外的表

users表

id  uname  upwd  mobile  book     

 

第三范式[3NF]

先满足2NF,所有的字段都必须直接依赖主键,而不能传递依赖

书本价格price依赖bookid,bookid依赖于id,price在传递依赖

违反第三范式,需要创建另外的表,通过外键约束

users表

id  uname  upwd  mobile  bookid  price

 


案例:

用户表:

id用户名密码

 

商品表:

id商品名称单价库存数量

订单项表   :

id商品ID  购买数量

 

订单表:    相当于一张小票,包含多个订单项

订单号用户ID时间订单项ID

4.表之间的关系

一对一

一对多

多对多

 

一对一的关系:

用户基本信息表:

idusernameuserpwd详细信息ID

 

用户详细信息表:

id真实姓名身份证号出生年月照片个性签名

 

 

一对多的关系:

班级表:

idbanjiNamebanjiDesc

 

学生表:

idstuNamesexagetelbanjiID  外键

 

多对多的关系:

学生表:  

idstuNamesexagetel

 

课程表:

idkechengNamescore

 

出现多对多的关系,需要建立一个中间表,将多对多拆分成多对一和一对多

选课表课程ID学生ID

 

 

  相关解决方案