数据库约束
对mysql数据库,共四种约束:unique,not null,primary key,foreign key。
1.使用列级约束语法建立约束:
create table test(
test_id int primary key,
test_name varchar(64) unique,
test_sex varchar(2) not null
);
2.使用表级约束语法建立约束
create table test(
test_id int,
test_name varchar(64),
test_sex varchar(2),
[constraint test_pk] primary key(test id),
constraint test_un unique(test_name,test_sex)
);
3.创建表后修改表结构时用add或modify增加约束
#使用add可以给多列组合用表级语法添加约束
alter table test
add unique(test_name,test_sex);
#使用modify只能给某一列用列级约束语法增加约束
alter table test
modify test_name varchar(12) not null;
#删除约束:alter table 表名 drop index 约束名
alter table test
drop index test_un;
#mysql对主键创建约束名没用,主键的约束名只能是primary key,因此删除主键约束的语法也和删除其他约束不一样
alter table test drop primary key;
#一般会对主键列设置自动增长功能,这样在该表中插入记录时可不为该列指定值,数据库系统会自动生成该列的值。
create table test(
test_id int auto_increment primary key,
test_name varchar(64) not null,
test_sex varchar(12) not null
);
外键约束
create table teacher(
teacher_id int auto_increment,
teacher_name varchar(64),
primary key(teacher_id)
);
create table student(
student_id int auto_increment primary key,
student_name varchar(64),
java_teacher int,
[constraint 外键名] foreign key(java_teacher) refernces teacher(teacher_id)
);
#删除外键:alter table 表名 drop foreign key 外键名
#如果没有设定外键名,外键名默认为 从表名_ibfk_n ,n从1开始。
alter table student drop foreign key 外键名/student_ibfk_1;
#增加外键
alter table student add foreign key(java_teacher) references teacher(teacher_id);
索引
索引在数据库中独立存放,但不能独立存在,必须属于某一个表。
1.索引的创建
自动创建:系统会自动为主键约束、唯一约束和外键约束创建索引。
手动创建
#create index 索引名 on 表名(列名,可以有多个)
create index student_name_idx on student(student_name);
2.索引的删除
drop index 索引名 on 表名
视图
创建视图
create or replace view view_test
as
(sql语句)select teacher_name from teacher
[with check option,该句的作用是让视图变成不可变];
删除视图
drop view view_test;
DML语句
DML语句作用:插入、修改、删除数据。
插入:
insert into 表名[(列名,可以是多列)]
values(第一条记录,每一列的值,列值之间以逗号隔开),
(第二条记录)...;
#带子查询的插入语句,可以插入多条记录,查询数据的源表和插入数据的目的表可以不是同一表,但两表的数据列个数要相等,数据类型要匹配。insert into teacher
select student_name from student;
修改:
update 表名
set column1=value1[,column2=value2,...]
[where condition];
删除:
删除不用指定列,因为总是整行整行删除
delete from 表名
[where condition];