MySQL完整性約束

2021-07-27 12:21:15 字數 1404 閱讀 7516

create

database adrui;

show databases;

use adrui;

/**not null : 非空約束, 插入資料該欄位不能為空*/

/**primary key : 主鍵約束(主鍵約束相當於非空約束 && 唯一約束, )*/

/**auto_increment是mysql擴充套件的字段值自加的約束,約束字段資料型別必須是整數(預設從1開始加, 或者從第一條記錄該字段的值開始自加)*/

/**default : 設定預設值的約束*/

create

table tmp(

v int

notnull,

id int

primary

key auto_increment,

*** varchar(7) default

'man'

);/**foreign key : 外來鍵約束, 字表中的某一記錄和父表的參照關係*/

/**(1)從表中的外鍵值必須在主表中存在

(2)從表中的外來鍵型別一定要和參照鍵(主表中的主鍵)型別一致,若為數#字,則要完全一致;若為字元,字元個數可以不一致。*/

create

table employ(

empno int

primary

key,

id int,

constraint fk_id foreign

key(id) references tmp(id);

);desc tmp;

desc employ;

/**父表*/

insert

into tmp(v) values(3, 1);

insert

into tmp(v, ***) values(3, 'woman');

/**字表:帶有外來鍵約束的資料插入*/

insert

into employ(empno, id) values(1, 1);

insert

into employ(empno, id) values(2, 2);

select * from tmp;

alter

table tmp drop v;

desc tmp;

alter

table tmp modify *** varchar(8);

desc tmp;

/*drop table tmp;*/

drop

database adrui;

show databases;

unique : 唯一約束, 字面意思

轉一篇外來鍵約束的文章 : mysql外來鍵約束

Mysql 完整性約束

定義 完整性約束是對字段進行限制,從而符合該欄位達到我們期望的效果比如字段含有預設值,不能是null等,主要有唯 一 自增 主鍵 外來鍵約束 唯一約束 唯一約束可以有多個但索引列的值必須唯一,索引列的值允許有空值。如果能確定某個資料列將只包含彼此各不相同的值,在為這個資料列建立索引的時候就應該使用關...

完整性約束

create table student tb id int notnull 非空約束 資料不允許為空 name varchar 255 null 顯式指定允許為空 新增非空約束 alter table 表名 modify column 屬性名 屬性型別 not null alter table s...

完整性約束

資料庫的完整性是指保護資料庫的有效性和正確性,防止資料庫中存在不符合語義的 不正確的資料。sql語言提供了相應的完整性約束機制,以確保將正確的資料儲存到資料庫中。完整性約束的型別 唯一約束 unique 用於表中的非主鍵字段,確保字段不會輸入重複的值,為其創造唯一索引 唯一鍵的值可以是null,但只...