计算机网络/计算机科学与应用/系统/运维/开发

MySQL建表(create table)命令详解

1、create table命令

在创建表之前,先选择数据库

创建表语法:

create table tablename(

col_name1 type auto_increment,

col_name2 type not null|null default val,

col_name3  type unique,

...,

primary key(col_name),

index idx_name(col_name1,col_name2,...),

foreign key(col_name) references tablename(col_name)

) engine=innoDB|myISAM default charset=字符集;


(1)type:定义字段的数据类型。其中:字符串类型(char,varchar)需要指定长度;整型(int,biging,tinyint等)和日期类型(datetime,timestamp等)只需要指定类型,不需要指定长度;decimal类型需要指定精度和小数位数。

(2)primary key参数指定表的主键。

(3)auto_increment参数指定字段为自增字段,该字段的类型必须为int或bigint才能设置为自增字段。

(4)not null|null参数设置字段能否取空值。

(5)default参数设置字段的默认值。

(6)index参数用来创建索引。idx_name指定索引名,该参数可以省略,如果省略则索引名就是字段名。

(7)foreign key参数用来指定外键。

(8)engine参数用来设置引擎类型,常用的有innoDB和myISAM引擎。

(9)default charset参数设置表所用的字符集。

创建emp表:

create table emp(

    emp_id int auto_increment,

    emp_name char(20) not null default '',

    birth datetime not null,

    phone char(20) not null,

    addr varchar(200) not null,

    dept_id int not null default 0,

    index idx_emp_name(emp_name),

    index idx_emp_name_birth(emp_name,birth),

    primary key(emp_id),               --emp_id字段为主键

    foreign key(dept_id) references dept(dept_id)

) engine=innoDB default charset=utf8;


人生建议:不要因为嘴硬而失去重要的东西,清醒,知趣,明得失,知进退。

评论

^