MySQL 列屬性(表的約束條件)

2021-08-28 08:49:03 字數 2878 閱讀 3035

表的建立

create table 表名

(列名a 資料型別(資料長度) 列級約束條件,

列名b 資料型別(資料長度) 列級約束條件,

列名c 資料型別(資料長度) 列級約束條件,

...表級約束條件(約束條件涉及到多個屬性列,則須定義在表級上)

);create table `runoob_tbl`(

`runoob_id` int unsigned auto_increment,

`runoob_title` varchar(100) not null,

`runoob_author` varchar(40) not null,

`submission_date` date,

primary key ( `runoob_id` )

)engine=innodb default charset=utf8;

常見的列屬性(約束條件constraints)

列屬性說明

null

沒有約束條件的預設值

not null

不允許為空

default

預設值unique

唯一值primary key

主鍵foreign key

外來鍵auto_increment

自增comment

注釋一、not null

欄位名 資料型別(資料長度) not null

phone int(12) not nul

二、default
欄位名 資料型別(資料長度) default 預設值

age int(10) default 18

三、unique

1、列級

欄位名 資料型別(資料長度) unique

id int(4) unique

2、表級

unique (欄位名)

create table department

( dpt_name char(20) not null,

people_num int(10) default '10',

unique (dpt_name),

);

四、primary key

1、列級

欄位名 資料型別(資料長度) primary key

id int(4) primary key

2、表級

primary key(列a,列b,...)

create table my_pri(

number char(10),

course char(10),

score tinyint,

primary key(number,course)--復合主鍵

)charset utf8;

3、追加主鍵。有兩種方式:

# 第一為修改表字段屬性;

alter table my_pri modify number char(11) primary key;

# 第二直接追加

alter table table_name add primary key(column) ;

alter table my_pri add primary key(number,course);--增加復合主鍵

alter table my_pri add constraint pk_score primary key(score)--使用關鍵字constraint 且指定主鍵名字pk_score

alter table my_pri add constraint primary key(score)--使用關鍵字constraint 且使用預設名字

五、foreign key
constraint 外鍵名(自定義) foreign key(外來鍵列)references 表名(外來鍵列指向的列)

create table department

( dpt_name char(20) not null, --外來鍵列指向的列

people_num int(10) default '10',

);create table employee

( id int(10) primary key,

name char(20),

in_dpt char(20) not null, --外來鍵列

constraint emp_fk foreign key (in_dpt) references department(dpt_name)

);

六、auto_increment
欄位名 資料型別(資料長度) auto_increment,

id int(10) auto_increment,

七、注釋

1、# 單行注釋

select 1+1;     # this comment continues to the end of line
2、-- 單行注釋(注意,-- 後要跟乙個空格)

select 1+1;     -- this comment continues to the end of line
3、/* */ 多行注釋

mysql> select 1 /* this is an in-line comment */ + 1;

mysql> select 1+

/*this is a

multiple-line comment

*/1;

列級別約束條件

約束 關聯式資料庫中二維表的每一列資料除了需要指定資料型別,有時還需要指定一些約束條件,來限制該列能夠儲存哪些資料。關聯式資料庫中主要存在五種約束 constraint 非空 唯 一 主鍵 外來鍵 檢查。約束有兩個級別 列級別和表級別。如果某個約束只對某個列有限制,就是列級別約束,如果某個約束與多個...

MySQL 約束條件

1 非空約束 not null規定某個欄位在插入的時候不能有null,標誌位非空的時候插入的時候必須給值,不然會報錯 2 唯一約束 unique規定某個字段在整個這一列中是唯一 3 主鍵 非空且唯一是主要特徵。主鍵可以唯一標識一行資料 可以從多行資料中定位到該資料 但是唯一標識一行資料的字段 或字段...

mySQL之約束條件

primary key pk 標識該字段為該錶的主鍵,可以唯一的標識記錄 foreign key fk 標識該字段為該錶的外來鍵 not null 標識該欄位不能為空 unique key uk 標識該字段的值是唯一的 auto increment 標識該字段的值自動增長 整數型別,而且為主鍵 de...