MySQL5:表结构

(二)表结构

  • 表1 – depart:
表:depart
idtitle
1开发
2运维
3销售
  • 表2 – info:
表:info
idnameemailagedepart_id
1名1name1@gmail.com101
2name2name2@qq.com201
3名3name3@gmail.com302
4nam4name4@163.com221
5joyjoy@gmail.com183
6joywonjoywon@gmail.com221
7wonwon@gmail.com301

1、一对多(约束关系)

  • 需要添加 外键(外键约束),可以在创建数据表过程中添加一个 外键约束,保证某一列的值必须数其他表中的特定列已经存在的值,例如:info.depart_id 的值必须是 depart.id 中已经存在的值

  • 示例:

    create table depart(
        id int not null primary key auto_increment,
        title varchar(16) not null
    )default charset=utf8;
    
    
    create table info(
        id int not null primary key auto_increment,
        name varchar(16) not null,
        email varchar(32) not null,
        age int,
        depart_id int not null,
        -- 约束 起个名字(fk_当前表名_关联表名) 外键 当前表(约束列) 参考 关联表(约束列)
        constraint fk_info_depart foreign key info(depart_id) references depart(id)
     )default charset=utf8;
    
  • 当前数据表我们已经在创建完成了,所以需要额外添加外键,因为是修改列的数据(所以用alter):

    alter table info add constraint fk_info_depart foreign key info(depart_id) references depart(id);
    
    
    -- 当添加外键约束时,999显然不在depart表中,所以会报错
    mysql> insert into info(name,email,age,depart_id) values("xx","xxx",20,999);
    
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test_sql`.`info`, CONSTRAINT `fk_info_depart` FOREIGN KEY (`depart_id`) REFERENCES `depart` (`id`))
    
  • 删除外键:

    alter table info drop foreign key fk_info_depart;
    
    -- 当删除外键时,999就成功插入数据行中
    mysql> alter table info drop foreign key fk_info_depart;
    Query OK, 0 rows affected (0.01 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    mysql> insert into info(name,email,age,depart_id) values("xx","xxx",20,999);
    Query OK, 1 row affected (0.00 sec)
    

2、多对多(约束关系)

  • 新建两个数据表(boy 和 girl)

    create table boy(
        id int not null primary key auto_increment,
        name varchar(16) not null
    )default charset=utf8;
    
    create table gril(
        id int not null primary key auto_increment,
        name varchar(16) not null
    )default charset=utf8;
    
  • 创建两者的关系表(bg)

    create table bg(
        id int not null auto_increment primary key,
        boy_id int not null,
        gril_id int not null,
        constraint fk_bg_boy foreign key bg(boy_id) references boy(id),
        constraint fk_bg_gril foreign key bg(gril_id) references gril(id)
    )default charset=utf8;
    
  • 删除外键

    alter table info drop foreign key fk_bg_boy;
    alter table ifo drop foreign key fk_bg_gril;
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值