mysql建表约束
mysql建表约束
删除某一行数据
- delete from user8 where id=3; 删除表user8中id为3的数据
展示选中的表
- show tables
删除数据表
-
DROP TABLE table_name
mysql建表约束
主键约束
-
能够唯一确定一张表中的一条记录,通过给某个字段添加约束,就可以使得该字段不重复且不user为空。
-
create table user(
id int primary key,
name varchar(20));
-
insert into user values(1,"张三");
insert into user values(1,"张三");
ERROR 1062 (23000): Duplicate entry '1' for key 'user.PRIMARY' -
mysql> insert into user values(2,"张三");
Query OK, 1 row affected (0.01 sec)mysql>
mysql> select * from user; -
id 也不能为空
insert into user values(null,"李四"); (不能执行 )
-
联合主键
create table user2(
id int,
name varchar(20),
password varchar(20),
primary key(id,name)
);
-
insert into user2 values(1,"王五","123");
insert into user2 values(2,"王五","123");
insert into user2 values(null,"李四","123"); #不能被执行,任何一个不能为空
-
联合主键:主键值只要加起来不重复就行
自增约束
-
create table user3(
id int primary key auto_increment,
name varchar(20)
);
insert into user3 (name) values("张三");
-
管控ID,自动增长
添加主键
-
create table user4(
id int,
name varchar(20)
);
alter table user4 add primary key(id);
-
alter table user4 drop primary key; 删除主键
-
alter table user4 modify id int primary key; 使用modify修改字段,添加约束
唯一约束
-
约束修饰字段的值不可以重复,两个键加起来不重复就行
create table user5(
id int,
name varchar(20)
);
alter table user5 add unique(name);
-
或者直接
create table user6(
id int,
name varchar(20),
unique(name));
-
或者直接在后面添加
create table user7(
id int,
name varchar(20),unique(name)
);
-
insert into user8 values(1,"杨子坑"),
insert into user8 values(1,"杨子"),
insert into user8 values(2,"杨子坑"),
均是可以运行的,只要加起来不重复即可
-
如何删除唯一约束?
alter table user8 drop index name;
-
通过modify添加
alter table user8 modify name varchar(20) unique;
-------------------------------总结------------------------------
- 1.建表时就添加约束
- 2.可以使用alter........add.....
- 3.alter.......drop......
- 4.删除 alter.....drop......
非空约束
-
修饰的字段不能为空 null
create table user9(id int,name varchar(20)not null);
mysql> insert into user9(name) values("lsi");
Query OK, 1 row affected (0.01 sec)mysql> insert into user9 (name) values("lsi");
Query OK, 1 row affected (0.01 sec)mysql> insert into user9 (id) values(3);
ERROR 1364 (HY000): Field 'name' doesn't have a default value
mysql>
默认字段
-
当插入字段值时
create table user10(
id int,
name varchar(20),
age int default 10);
-
insert into user10 (id,name) values(1,"杨子");
外键约束
-
涉及两个表:父表,子表
-
主表,副表
-
班级表
create table classes(
id int primary key,
name varchar(20))
-
学生表
create table students(
id int primary key,
name varchar(20),
class_id int,
foreign key(class_id) reference classes(id));
-
数据录入
insert into classes values(1,"一班");
insert into classes values(2,"二班");
insert into classes values(3,"三班");
insert into classes values(4,"四班");
insert into students values (1001,"张三",1);
insert into students values (1002,"张三",2);
insert into students values (1003,"张三",3);
insert into students values (1004,"张三",4);
insert into students values (1005,"张三",5); #父表中没有所以不能被执行
总结:
- 主表(父表)classes中没有的数据值,在副表(子表)中,是不可以使用的。
- 主表中的记录被副表引用时,是不可以被删除的。(delete from classes where id=4);