+------------+---------+------+| name | teacher | id |+------------+---------+------+| DataMining | Shao |1|| Runing | Hao |3|+------------+---------+------+
主键约束primary key
主键可以唯一确定一条数据,字段值不可重复
创建主键在 类型后+primary key
修改为主键
altertable course modify id intprimarykey;
mysql>desc course;+-------------+--------------+------+-----+---------+-------+| Field |Type|Null|Key|Default| Extra |+-------------+--------------+------+-----+---------+-------+| id |int(11)|NO| PRI |NULL||| courseTitle |varchar(255)| YES ||NULL||| teacher |varchar(255)| YES ||NULL||| timeTable |varchar(0)| YES ||NULL||+-------------+--------------+------+-----+---------+-------+4rowsinset(0.05 sec)
mysql>altertable course dropprimarykey;
mysql>altertable course addprimarykey(id);
联合主键
且的关系,两个主键都相同的数据不行
有一个相同可以
mysql>createtable student2(-> id int(10),-> name varchar(20),-> password varchar(20),->primarykey(id,name));
自增约束
结合主键使用,可以自动赋值
mysql>insertinto student2
->values(NULL,"mari");
Query OK,1row affected (0.00 sec)
mysql>select*from student2;+----+------+| id | name |+----+------+|1| mari |+----+------+1rowinset(0.04 sec)
唯一约束
字段值唯一(与Primary key区别:unique 可为空,最多一处空)
mysql>altertable student3 addunique(name);
Query OK,0rows affected (0.03 sec)
Records: 0 Duplicates: 0Warnings: 0
mysql>desc student3;+-------+-------------+------+-----+---------+-------+| Field |Type|Null|Key|Default| Extra |+-------+-------------+------+-----+---------+-------+| id |int(20)| YES ||NULL||| name |varchar(20)| YES | UNI |NULL||+-------+-------------+------+-----+---------+-------+
mysql>altertable student3 dropindex name;//删除unique约束
非空约束
修饰的字段不可为空
mysql>createtable stu4(-> id int(20),-> name varchar(20)notnull->);
默认约束
插入字段值时,没有传值就会使用默认值
外键约束
链接它表的键
mysql>altertable student addforeignkey(class_id)references course(id);
mysql>desc student;+----------+--------------+------+-----+---------+-------+| Field |Type|Null|Key|Default| Extra |+----------+--------------+------+-----+---------+-------+| id |int(11)|NO| PRI |NULL||| name |varchar(255)| YES ||NULL||| number |varchar(0)| YES ||NULL||| class_id |int(11)| YES | MUL |NULL||+----------+--------------+------+-----+---------+-------+