• SQL之mysql到hive批量生成建表语句


    目录

    一、需求

    二、实现步骤

    1.数据类型转换维表

    2.sql批量生成建表语句


    一、需求

    数据采集时如果使用datax的话,必须先手工建好表之后才能进行数据采集;使用sqoop的话虽然可以默认建表,但是每次还要手工配置命令。表数量不多的话还好,如果多库多表需要批量采集的话工作量会很大,因此需要一个批量生成建表语句的功能来节省人力。

    二、实现步骤

    1.数据类型转换维表

    先确定好异构数据源的数据类型转换关系,可以定义好一张维表。

    CREATE TABLE dim_data_type_convert
        (
            source string comment '源库',
            source_data_type string comment '源库数据类型',
            target string comment '目标库',
            target_data_type string comment '目标库数据类型',
            update_time string comment '更新时间'
        )
    COMMENT='数据类型转换维表';

    数据示例如下:

    源库源库数据类型目标库目标库数据类型更新时间
    mysqlbiginthivebigint20220817
    mysqlinthivebigint
    mysqltinyinthivebigint
    mysqlcharhivestring
    mysqlvarcharhivestring
    mysqldatetimehivedatetime
    mysqldecimalhivedouble
    mysqldoublehivedouble
    mysqlfloathivedouble
    mysqljsonhivestring
    mysqlmediumtexthivestring
    mysqltexthivestring
    mysqltimehivestring
    mysqltimestamphivetimestamp
    mysqlvarbinaryhivebinary
    mysqlbinaryhivebinary

    2.sql批量生成建表语句

    1. SELECT
    2. a.TABLE_NAME ,
    3. b.TABLE_COMMENT ,
    4. concat('CREATE TABLE IF NOT EXISTS ',a.TABLE_NAME ,' (',group_concat(concat(a.COLUMN_NAME,' ',
    5. c.target_data_type," COMMENT '",COLUMN_COMMENT,"'") order by a.TABLE_NAME,a.ORDINAL_POSITION) ,
    6. ") COMMENT '",b.TABLE_COMMENT ,"' ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t' STORED AS orc;") AS DDL
    7. FROM
    8. (
    9. SELECT
    10. TABLE_SCHEMA,
    11. TABLE_NAME,
    12. COLUMN_NAME,
    13. ORDINAL_POSITION,
    14. DATA_TYPE,
    15. COLUMN_COMMENT
    16. FROM information_schema.COLUMNS
    17. WHERE TABLE_SCHEMA='你的库名'
    18. ) a
    19. LEFT JOIN information_schema.TABLES b
    20. ON a.TABLE_NAME=b.TABLE_NAME
    21. AND a.TABLE_SCHEMA=b.TABLE_SCHEMA
    22. --源库为mysql,目标库为hive
    23. LEFT JOIN
    24. (
    25. select
    26. *
    27. from dim_data_type_convert
    28. where source='mysql' and target='hive'
    29. ) c
    30. ON a.DATA_TYPE=c.source_data_type
    31. where b.TABLE_TYPE='BASE TABLE'
    32. GROUP BY
    33. a.TABLE_NAME,
    34. b.TABLE_COMMENT
    35. ;

    生成示例:

    TABLE_NAMETABLE_COMMENTDDL
    TABLE_NAMETABLE_COMMENT

    CREATE TABLE IF NOT EXISTS TABLE_NAME

    (COLUMN_NAME target_data_type COMMENT “COLUMN_COMMENT”)

     COMMENT "TABLE_COMMENT "

    ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\t'

    STORED AS orc;

  • 相关阅读:
    proxy解决跨域问题
    Unity之管理自己的Unitypackages
    WCET学习(二)
    数据爬取...
    如何成为提示词工程师(精简版)
    使用Vue + axios实现图片上传,轻松又简单
    《算法竞赛进阶指南》 临值查找
    深入探索(淘宝1688京东)API商品详情数据:从价格到销量,一应俱全
    SpringBoot的Cacheable缓存问题一则
    SpringBoot自动装配源码分析
  • 原文地址:https://blog.csdn.net/chimchim66/article/details/126381504