拆表、关联表

拆表

先创建表格
create table if not exists goods_cates(
    id int unsigned primary key auto_increment,
    name varchar(40) not null,
);
查询goods表中商品的种类
select cate_name from goods group by cate_name;
将分组结果写入到goods_cates数据表
insert into goods_cates (name) select cate_name from goods group by cate_name;
拆表.png

将第一张表和竖着的第二张的关联

通过alter table语句修改表结构
alter table goods  
change cate_name cate_id int unsigned not null;
(先将数据类型改成一致的)
然后再通过外键将他们关联起来
alter table goods add foreign key (cate_id) references goods_cates(id);

作业:第一张表的与第三张表的拆分及关联

拆分
先创建表格
create table if not exists goods_brand(
    id int unsigned primary key auto_increment,
    name varchar(40) not null
);
查询goods表中商品品牌
select brand_name from goods group by brand_name;
将分组结果写入到goods_brand数据表
insert into goods_brand (name) select brand_name from goods group by brand_name;

关联
alter table goods  
change brand_name brand_id int unsigned not null;
alter table goods add foreign key (brand_id) references goods_bramd(id);

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 最后一次去大兴了,还剩下一些旧书,本打算卖了,房屋交接后,却忘了去取钱,好吧,书是无价的。 最后看一眼吧,我们在北...
    星空下的悠游阅读 173评论 1 3
  • 很怕会让人说我小气 所以我假装大方,分发自己的东西 然而,最后只剩下一点,我开始心疼了 又要当婊子,又要立牌坊,自...
    未望人阅读 223评论 0 0
  • 排解焦虑的最好方法,就是立即行动。不要质疑自己的能力,相信你远比想象得更强大;不要把时间都留给游戏、网络,让书本和...
    KUNbehappy阅读 179评论 0 0
  • 朋友在群里分享了一篇文章,大致意思是: “漂亮妹子都是会呼吸的人民币”, “不化妆就去上班,是对整个公司的一种失望...
    枕藏写影视阅读 349评论 2 1
  • 今早起床看书,书中有这么一句话: 钱心跟着人心走。全世界最聪明的人最终都是先研究人心和制度,反过来才能驾驭金钱。 ...
    小easy阅读 236评论 2 2