mysql一张表拆成多张表思路方案实现

起始是同学有个需求,怎么实现一张拆成多张表,同时数据也拆好。所有如下探究,简化数据和例子

1、先决条件

  • 图示

    在这里插入图片描述

  • mysql 数据库

  • mysql初始化数据

    • create table A
      (
          no   int auto_increment
              primary key,
          name varchar(30) null,
          de   varchar(30) null
      );
      
      INSERT INTO A (no, name, de) VALUES (1, '赵', '部门一');
      INSERT INTO A (no, name, de) VALUES (2, '钱', '部门一');
      INSERT INTO A (no, name, de) VALUES (3, '孙', '部门一');
      INSERT INTO A (no, name, de) VALUES (4, '李', '部门二');
      INSERT INTO A (no, name, de) VALUES (5, '周', '部门二');
      INSERT INTO A (no, name, de) VALUES (6, '吴', '部门二');
      INSERT INTO A (no, name, de) VALUES (7, '郑', '部门三');
      INSERT INTO A (no, name, de) VALUES (8, '王', '部门三');
      
      
    • 注释

      • 创建一张表A, 三个字段,no:编号,name:姓名, de:部门名
    • 需求按de(部门)拆成多张表,暂且以de的值为表名,sql语句怎么实现?

    • 效果图

    • image-20201206144846877

2、思路

  • mysql有create select 语法,只是支持生一张表,但是这个是不确定多少个部门的
  • 利用select语句自动生成 create select 语句,复制一下就完成分表操作

3、实操

3.1、create select 语句

create table  新表名 select 字段1, 字段2 from 原表名 where 条件;

例子(比如分开部门一所有数据):
create table  部门一 select no, name from A where de='部门一';

3.2、生成一条create table 语句

select  CONCAT('create table  ', de, ' select no, name from A where de=''', de, ''';')  as tab from A limit 1
  • concat : 拼接字符函数

  • 效果:

    • image-20201206151119012

3.3、生成所有create table 语句,去重 (通过group by去重)

select  CONCAT('create table  ', de, ' select no, name from A where de=''', de, ''';')  as tab from A group by  de 
  • 效果
  • image-20201206151348793

3.4、继续优化,如果100个部门不得复制一百遍吗?能不能将tab的值拼接起来

  • group_concat 字段名 SEPARATOR  分隔符
    
  • 生成sql

  • select group_concat(aa.tab SEPARATOR ' ')from
    
    (select  CONCAT('create table  ', de, ' select no, name from A where de=''', de, ''';')  as tab from A group by  de ) aa;
    
  • 结果是:

    • create table  部门一 select no, name from A where de='部门一'; create table  部门二 select no, name from A where de='部门二'; create table  部门三 select no, name from A where de='部门三';
      

3.5、复制执行即可。

4、总结

  1. 本质上是利用mysql的select语句拼接SQL,替换手动拼接sql的麻烦和容易出错
  2. 然后利用mysql支持语句执行sql功能。例如其他需求,比如订正数据时候,可以利用select生update语句,然后执行,这也一个思路,当然配合excel使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值