MySQL(二)

1、表的约束

1.1、null

null 表明该列内容可以为空(不指明not null时,默认为null)
not null 该列内容不能为空
mysql> create table if not exists t1(
    -> id tinyint unsigned not null,
    -> name varchar(20)
    -> );

1.2、default

default:即缺省值,对某列指明缺省值时,如果插入数据时,不指明内容,就默认使用缺省值。(缺省值可以是null,MySQL默认就是null)。

mysql> create table if not exists t2(
    -> id int unsigned,
    -> gender varchar(20) default '男'
    -> );

1.3、comment

comment:就是列描述,相当于注释。

1.4、zerofill

zerofill:即0填充。

比如:int(5) zerofill,那么显示数据时,空位置用0填充。

比如数据是5,显示结果就是00005(高版本MySQL可能不显示了)。

1.5、key

1.5.1、primary key

primary key:即主键。

主键数据,用来约束一张表里面的该字段,不能为空,并且数据不能重复。

一张表只能有一个主键(不是说只能给一列设置主键)!!

单主键:该列不允许重复数据。

复合主键:比如给两列同时设置主键,这两列数据不能同时重复。

主键的创建:

1、建表时就创建,直接在该行后面增加primary key

mysql> create table if not exists t3 (
    -> id tinyint  unsigned primary key,
    -> name varchar(20) not null
    -> );

2、建表后追加:alter table table_name add primary key(field_name)

mysql> create table if not exists t4
    -> (id tinyint unsigned);
Query OK, 0 rows affected (0.04 sec)

mysql> alter table t4 add primary key(id);
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

主键的删除:因为主键只有一个,直接删除即可

alter table table_name drop primary key;

1.5.2、auto_increment

自增长:即每次插入一个数据,该内容自动增长1。

当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。通常和主键搭配使用,作为逻辑主键。

注意:

1、一个字段想要是自增长,前提它必须是一个索引(key一栏有值)。

2、自增长字段必须是整数。

3、一张表只能有一个自增长。

mysql> create table if not exists t5(
    -> id tinyint unsigned primary key auto_increment,
    -> name varcha
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YangZ123123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值