关系型数据库:插入数据时,一定要满足一定的规范,标准。write on schema
schema:表的定义,主键的定义,外键的定义,列也定义好了
一、创建学生student 表
create table student(
id int,
name varchar(255),
age int,
gender char(1)
)
1.insert
insert into student(id,name,age) values(1,'zs',20);
2.update
update student set name='wangwu',age=22 ;
where id=2;
3.delete
delete from student where id=2;
使用delete删除表格数据较慢,使用truncate删的快,但是慎用!!!
truncate tanle student;
4.drop
删除表。一般情况下不会去删除整个表
drop table student;
二、约束
约束就是数据库中数据在入库之前,保证数据的完整性,合法性。
1.主键约束PRIMARY KEY
(1)如何选取主键:
使用逻辑主键:唯一,不允许使用又业务含义是属性。(例如省身份证号,银行卡号)
有时需使用联合主键,一列无法保证唯一,需要两列或更多
(2) 新建表时设置主键自增
drop table if exists student;
create table student(
id int primary key auto_increment,
name varchar(255),
age int
);
另一种写法:
drop table if exists student;
create table student(
id int auto_increment,
name varchar(255),
age int,
primary key(id)
);
(3)新建后插入数据
insert into student values(1,’zhangsan‘,12);
插入数据后再插入id为1的学生数据,由于设置了主键,不允许插入
insert into student values(1,’zhangsan‘,12);
2.外键约束FOREIGN KEY
表和表之间唯一的联系。外键关系保证引用完整性
student相当于父表,score相当于子表;先创建附表,再创建子表
(1)创建学生表和学生成绩表
drop table if exists score;
drop table if exists student;
create table student(
id int auto_increment,
name varchar(255),
age int,
primary key (id)
);
create table score(
id int primary key auto_increment,
student_id int,
html int,
liunx int,
FOREIGN KEY (student_id) REFERENCES student(id)
);
(2)查看两个表并给学生表插入数据
desc student;
desc score;
insert into student(name,age) values('zhangsan',20);
insert into student(name,age) values('lisi',30);
insert into student(name,age) values('wangwu',20);
select * from student;
(3)给score表插入数据
insert into score(html,liunx,student_id) values(90,90,2);
注意:学生成绩表中的数据,学生必须是在学生表中存在的学生
再次插入数据时,由于不存在编号student_id为4的学生,所以报错
insert into score(html,liunx,student_id) values(90,90,4);
3.DEFAULT默认约束、非空约束 NOT NULL、唯一约束UNIQUE
drop table student;
drop table score;
create table student(
id int primary key auto_increment,
name varchar(255) default 'zhangsan',
age int not null,
email varchar(255) unique
);
(1)DEFAULT
查看student表,会看到name默认为zhangsan
desc student;
插入信息
insert into student(name,age) values('lisi',20);
(2)NOT NULL非空约束
insert into student(name) values('zhangsan');
由于age没有默认数值,且NOT NULL非空,所以在没有输入age的情况下无法插入数据
(3)UNIQUE唯一约束
insert into student(age,email) values(20,'[email protected]');
添加后继续添加
insert into student(age,email) values(20,'[email protected]');
此时由于邮箱email设置为唯一UNIQUE,添加失败。