mysql>createtable class (-> id intprimarykey,-> name varchar(20)notnull->);
Query OK,0rows affected (0.04 sec)
mysql>createtable student (-> id intprimarykey,-> name varchar(20)notnull,-> email varchar(20)default'unknow',-> QQ varchar(20)unique,-> classId int,foreignkey(classId)references class(id)->);
Query OK,0rows affected (0.03 sec)
mysql>desc class;+-------+-------------+------+-----+---------+-------+| Field |Type|Null|Key|Default| Extra |+-------+-------------+------+-----+---------+-------+| id |int(11)|NO| PRI |NULL||| name |varchar(20)|NO||NULL||+-------+-------------+------+-----+---------+-------+2rowsinset(0.02 sec)
mysql>desc student;+---------+-------------+------+-----+---------+-------+| Field |Type|Null|Key|Default| Extra |+---------+-------------+------+-----+---------+-------+| id |int(11)|NO| PRI |NULL||| name |varchar(20)|NO||NULL||| email |varchar(20)| YES || unknow ||| QQ |varchar(20)| YES | UNI |NULL||| classId |int(11)| YES | MUL |NULL||+---------+-------------+------+-----+---------+-------+5rowsinset(0.00 sec)
check(了解)
作为了解,类似java中的枚举,保证列中的值符合指定的条件
MySQL使用时不报错,但忽略该约束:
createtable test_user (
id int,
name varchar(20),
sex varchar(1),check(sex ='男'or sex='女'));
auto_increment 自增
自增特点:
如果表中没有记录,自增从一开始
如果有数据,从上一条记录往下自增
插入再删掉数据,自增的值不会重复利用,会按删掉的那条开始自曾
mysql>createtable test (-> id intprimarykeyauto_increment,-> name varchar(20)->);
Query OK,0rows affected (0.02 sec)
mysql>insertinto test values(null,'a');
Query OK,1row affected (0.01 sec)
mysql>select*from test;+----+------+| id | name |+----+------+|1| a |+----+------+1rowinset(0.00 sec)
mysql>deletefrom test where id =1;
Query OK,1row affected (0.01 sec)
mysql>insertinto test values(null,'a');
Query OK,1row affected (0.00 sec)
mysql>select*from test;+----+------+| id | name |+----+------+|2| a |+----+------+1rowinset(0.00 sec)