關系型資料庫:插入資料時,一定要滿足一定的規範,标準。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,添加失敗。