数据表的基本操作
- 创建表
- 查看表
- 约束
3.1 使用主键约束
3.2 使用外键约束
3.3 唯一约束
3.4 使用非空约束
3.5 使用默认约束条件 - 自动增加
- 查看表结构
- 查看表的结构
- 修改数据表
7.1 修改表名
7.2 修改字段的数据类型
7.3 修改字段名
7.4 添加字段
7.5 删除字段
7.6 修改字段的排列位置
7.7 更改表的存储引擎
7.8 删除表的外检约束
7.9 删除表里面的所有数据 - 删除数据表
8.1 删除没有被关联的表
8.2 删除被其他表关联的主表
1. 创建表
create table <表名>;
2. 查看表
show tables;
3. 约束
3.1 使用主键约束
关键词:primary key
主键可以是表中的一列或多列的组合。唯一,不为空,一个表只能有一个主键。
/*单字段主键使用
定义列同时指定主键*/
create table <表名>(
id int(11) primary key
);
/*单字段主键使用
定义列后指定主键*/
create table <表名>(
id int(11),
primary key(id)
);
/*多字段联合主键*/
create table <表名>(
id int(11),
name varchar(20),
primary key(id,name)
);
3.2 使用外键约束
一个表可以有一个或多个外键,外键必须等于另一个表的主键。可以为空。
注意:
1、主键所在的表是主表。
2、外键所在的表是从表。
/*主表*/
create table tb1(
id int(11) primary key,
name varchar(20) not null,
location varchar(50)
);
/*从表*/
create table tb2(
id int(11) primary key,
name varchar(25),
deptid int(11),
salary floar,
constraint fk_deptid foreign key(deptid) references tb1(id)
);
3.3 唯一约束
关键词:unique
例如:
/*方法一*/
create table <表名>(
name varchar(20) unique
);
/*方法二*/
create table <表名>(
name varchar(20),
constraint sth unique(name)
);
unique和primary key 的区别:
- 一个表中可以有很多个字段声明为unique,但只能有一个primary key声明。
- primary key 不能为空值。unique可以为空值(null)。
3.4 使用非空约束
关键词:not null
create table <表名>(
name varchar(20) not null
);//name 值不能为空
3.5 使用默认约束条件
关键词:default
create table <表名>(
deptid int(11) default 1111
);//deptid 默认值为1111
4.自动增加
关键词:auto_increment
create table <表名>(
id int(11) primary key auto_increment,
);
5.查看表结构
关键词:describe | desc
describe <表名>; | desc <表名>;
6.查看表的结构
关键词:show create table
show create table <表名>;
7. 修改数据表
7.1 修改表名
关键词:rename
alter table <旧表名> rename <新表名>;
7.2 修改字段的数据类型
关键词:modify
alter table <表名> modify <字段名> <数据类型>
7.3 修改字段名
关键词:change
alter table <表名> change <旧字段名> <新字段名> <新数据类型>;
7.4 添加字段
关键词:add
alter table <表名> add <新字段类型> <数据类型> [约束条件] [first|(after 已存在字段名)];
- 添加无完整性约束的字段
alter table tb1(表名) add id int(11);
添加有完整性约束条件的字段
alter table tb1(表名) add id int(11) not null;
在表的第一列添加一个字段
alter table tb1(表名) add id int(11) first;
- 在表的指定列之后添加字段
alter table tb1(表名) add id int(11) after name;
7.5 删除字段
关键词:drop
alter table <表名> drop <字段名>;
7.6 修改字段的排列位置
关键词:modify
alter table <表名> modify <字段1> <数据类型> first|(after <字段2>);
7.7 更改表的存储引擎
关键词: engine
alter table <表名> engine <更改后的存储引擎名>
7.8 删除表的外检约束
关键词:drop foreign key
alter table <表名> drop foreign key <外键约束名>;
7.9 删除表里面的所有数据
关键词:delete
delete from <表名>;
8. 删除数据表
关键词:drop
8.1 删除没有被关联的表
drop table [if exists] 表1,表2,表3...表n;
for example:
drop table if exists tb1;
注意:若无 if exists时,若果表不存在,sql语句不能顺利执行。若 if exists 存在时,sql语句可以顺利执行,并且会报警告。
8.2 删除被其他表关联的主表
注意:直接删除主表会显示失败。应该先删除从表或者解除关联的表的外检约束条件。
/*方法一:删除从表*/
drop table tb2;
drop table tb1;
/*方法二:解除关联的表的外键约束条件*/
alter table tb2 drop foreign key fk_deptod;
drop table tb1;