一、MySQL创建、修改表,有2种方式:
1、在图形界面工具中点击菜单提示进行操作,如:
2、使用SQL语句操作,如下:
-- 切换数据库
use sh;
-- 如果存在就删除表
drop table if exists room;
-- 如果表不存在就创建表,room是表名,rid列名
create table if not exists room(
rid int primary key,-- primary key设置列为主键
rname varchar(50) not null,-- not null该列数据不能为空
beds int,
address varchar(255));
-- 查看表所有列的信息
describe room;
-- 修改表,添加主键约束
alter table student
add constraint c_id primary key(sid);-- constraint约束,c_id表示约束的名字,sid表示在student表中添加为主键的列
3、修改表的用法:
1)添加列:
<span style="font-size:12px;">-- 添加列,默认最后一列
alter table student add column adfiy varchar(50);
-- 添加列,指定位置:第一列
alter table student add column sex int first;
-- 添加列,指定位置:name列的后面
alter table student add column major int after name;</span>
2)修改列:
a)修改列的名称:
-- 修改列的名称,相当于把之前的列删除,再添加列
alter table student change column adfiy adfies varchar(10);
b)修改列的类型:
<span style="font-size:12px;">alter table student modify column adfiy varchar(10);</span>
3)删除列:
<span style="font-size:12px;">alter table student drop column adfies;</span>
4)重命名表:
<span style="font-size:12px;">alter table student rename to students;</span>
二、MySQL中表的约束(使用关键字constraint):
1、主键约束:主键列不能为null 且唯一,创建表和修改表时指定主键的方式,如上面的代码。
2、唯一约束:非主键列唯一。
1)创建表时指定唯一约束:
create table if not exists room(
rid int primary key,
rname varchar(50) not null,
beds int,
address varchar(255),
bossId int,
-- constraint约束关键字 unique_name定义的约束名称 unique是唯一约束关键字,rname表示约束的列
constraint unique_name unique (rname));
2)修改表时,添加唯一约束:
alter table room
add constraint unique_name unique(beds);
3、外键约束:约束引用其他表主键的列,该列的值只能是主键列的值。创建表时指定外键约束:
drop table if exists room;
create table if not exists room(
rid int primary key,
rname varchar(50) not null,
beds int,
address varchar(255),
bossId int,
-- constraint约束关键字 fk_name定义的约束名称 foreign key是外键约束关键字
constraint fk_name foreign key (bossId)
references student(sid) -- references指定约束
);