Home > Database > Mysql Tutorial > body text

MySQL学习笔记4:完整性约束_MySQL

WBOY
Release: 2016-06-01 13:37:27
Original
1343 people have browsed it

bitsCN.com

完整性约束是对字段进行限制,从而符合对该属性进行操作的特定要求

通俗点说:如果你的数据不满足我这一字段的要求,数据库系统就拒绝执行操作

 

设置表的主键

主键能够标识表中每条信息的唯一性,如同身份证号码和人的关系

人可以同名,但是身份证号码却是唯一的,

创建主键的目的在于快速查找到表中的某一条信息

 

单字段主键
mysql> create table student(    -> id int primary key,    -> name varchar(20),    -> sex boolean    -> );Query OK, 0 rows affected (0.09 sec)
Copy after login

创建了三个字段,其中id为主键

 

多字段主键

多字段主键由多个属性组合而成,在属性定义完之后统一设置主键

mysql> create table student2(    -> id int,    -> course_id int,    -> score float,    -> primary key(id,course_id)    -> );Query OK, 0 rows affected (0.11 sec)
Copy after login

student2表有三个字段,其中id和course_id的组合可以确定唯一的一条记录

 

设置表的外键

表的外键与主键是相对应的,比如表A中的id是外键,表B中的id是主键

那么就可以称表B为父表,表A为子表

设置表外键的作用在于建立与父表的联系,比如表B中id为123的学生删除后,表A中id为123的记录也随着消失

这样做的目的在于保证表的完整性

mysql> create table student3(    -> id int primary key,    -> course_id int,    -> teacher varchar(20),    -> constraint fk foreign key(id,course_id)    -> references student2(id,course_id)    -> );Query OK, 0 rows affected (0.12 sec)
Copy after login

这里创建student3表,constraint后面的fk是外键别名,foreign key也就是设置外键的字段

references后的内容表示父表,和父表中的主键

需要注意的是,父表中的主键不能为空,并且主键和外键的数据类型要一致

 

设置表的非空约束

非空性很好理解,就是设置表中字段的值不能为空(NULL)

如果在已经设置此约束性条件的字段中插入空值,数据库系统则会报错

mysql> create table student4(    -> id int not null,    -> name varchar(20),    -> sex boolean    -> );Query OK, 0 rows affected (0.10 sec)
Copy after login

这里的not null就是约束条件

 

设置表的唯一性约束

唯一性是指表中该字段的值不能重复出现,设置表的唯一性约束

也就是给表中某个字段加上unique

mysql> create table student5(    -> id int unique,    -> name varchar(20)    -> );Query OK, 0 rows affected (0.10 sec)
Copy after login

此处id字段便不可重复

 

设置表的属性值自动增加

auto_increment主要用于为表中插入的新记录自动生成唯一的ID

一个表只能有一个字段使用auto_increment约束

并且该字段必须为主键的一部分

mysql> create table student6(    -> id int primary key auto_increment,    -> name varchar(20)    -> );Query OK, 0 rows affected (0.12 sec)
Copy after login

这里的id是主键,并且会自动增加id值,比如1,2,3,4……

需要注意的是,auto_increment约束的值必须是整数类型

 

设置表中属性的默认值

在表中插入一条新的记录时,如果没有为该字段赋值

那么数据库系统会自动为该字段赋上一条默认值

mysql> create table student7(    -> id int primary key,    -> score int default 0    -> );Query OK, 0 rows affected (0.10 sec)
Copy after login

此处的score字段便会默认为0

 

 

bitsCN.com
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!