insert into 表名 values(1,‘张三’); insert into 表名 values(1,‘张三’); 第二次添加报错,主键不可添加重复 insert into 表名 values(1,‘张三’);不可为空也会报错 联合主键只要组合加起来不一样即可,但都不可以为空
create table 表名( id int, name varchar(20) primary key(id,name) );insert into 表名 values(1,‘张三’); insert into 表名 values(2,‘张三’); 此种情况 联合主键不会报错
insert into 表名 (name) values(‘张三’); insert into 表名 (name) values(‘张三’); 此时虽然没有添加ID,但是自增约束与主键约束结合,自动生成ID
如果事前没有加主键约束的办法
create table 表名( id int, name varchar(20) ); alter table 表名 add primary key(id);删除主键方法
create table 表名( id int primary key, name varchar(20) ); alter table 表名 drop primary key(id);使用 modify 修改字段,添加约束
create table 表名( id int, name varchar(20) ); alter table 表名 modify id int primary key;约束修饰的字段的值不可以重复,重复就报错
create table 表名( id int, name varchar(20) ); alter table 表名 add unique(name);两个键组合不重复就可以
create table 表名( id int, name varchar(20) unique(name,id) ); create table 表名( id int, name varchar(20) unique );删除唯一约束方法
create table 表名( id int, name varchar(20) unique(name) ); alter table 表名 drop index name;当我们插入字段值的时候,如果没有传值,就会使用默认值 增加与删除与前几个一样
create table 表名( id int , name varchar(20) age int default 10 );涉及到:父表,子表 主表,副表 –班级
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) references classes(id) ); ``` ```sql 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,'lisi',5);X主表中不存在 副表会报错 主表中的记录被副表引用,是不可以被删除的 Xdelete from classes where id = 4;
https://www.bilibili.com/video/av39807944?p=15看到第16节课
