MySQL创建、修改表、表的约束

一、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指定约束
);



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值