zoukankan      html  css  js  c++  java
  • mysql 修改表的字段

    修改一个表的字段

    ALTER TABLE `member` CHANGE `memberid` `memberid` bigint unsigned;

    修改含有外键的字段

    -- 执行 begin 到 end 之间的代码可能需要修改sql_mode值
    show variables like '%sql_mode'
    -- 保存查询出来的sql_mode 值
    set global sql_mode=''
    set session sql_mode=''
    
    -- begin
    set group_concat_max_len = 2048;
    set @table_name ="member";
    set @change ="bigint unsigned";
    set @table_id = "memberid";
    select distinct table_name,
     column_name,
     constraint_name,
     referenced_table_name,
     referenced_column_name,
     CONCAT(
     GROUP_CONCAT('ALTER TABLE ',table_name,' DROP FOREIGN KEY ',constraint_name SEPARATOR ';'),
     ';
    ',
     GROUP_CONCAT('ALTER TABLE `',table_name,'` CHANGE `',column_name,'` `',column_name,'` ',@change SEPARATOR ';'),
     ';
    ',
     CONCAT('ALTER TABLE `',@table_name,'` CHANGE `',@table_id,'` `',@table_id,'` ',@change),
     ';
    ',
     GROUP_CONCAT('ALTER TABLE `',table_name,'` ADD CONSTRAINT `',constraint_name,'` FOREIGN KEY(',column_name,') REFERENCES ',referenced_table_name,'(',referenced_column_name,')' SEPARATOR ';')
     ) as query
    from information_schema.key_column_usage
    where referenced_table_name is not null
     and referenced_column_name is not null
     and referenced_table_name = @table_name
     group by referenced_table_name
    -- end
    
    -- 恢复
    set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    set global sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    

    执行begin到end之间的代码会得到 query 代码:

    ALTER TABLE member_weixin DROP FOREIGN KEY member_weixin_ibfk_1;ALTER TABLE member_qq DROP FOREIGN KEY member_qq_ibfk_1;ALTER TABLE member_visitor DROP FOREIGN KEY member_visitor_ibfk_1;
    ALTER TABLE `member_weixin` CHANGE `memberid` `memberid` bigint unsigned;ALTER TABLE `member_qq` CHANGE `memberid` `memberid` bigint unsigned;ALTER TABLE `member_visitor` CHANGE `memberid` `memberid` bigint unsigned;
    ALTER TABLE `member` CHANGE `memberid` `memberid` bigint unsigned;
    ALTER TABLE `member_weixin` ADD CONSTRAINT `member_weixin_ibfk_1` FOREIGN KEY(memberid) REFERENCES member(memberid);ALTER TABLE `member_qq` ADD CONSTRAINT `member_qq_ibfk_1` FOREIGN KEY(memberid) REFERENCES member(memberid);ALTER TABLE `member_visitor` ADD CONSTRAINT `member_visitor_ibfk_1` FOREIGN KEY(memberid) REFERENCES member(memberid)

    执行query代码,即修改了字段。并且外键保持不变

  • 相关阅读:
    css3skew
    github如何使用
    互联网历史
    html知识点
    人类的终极目标是什么?
    如何提高自我学习能力?
    为什么富人越富,穷人越穷?
    关于游戏小说与学习知识的不同
    关于写代码的一点体会
    监听多行文本框字数输入
  • 原文地址:https://www.cnblogs.com/dzqdzq/p/9760191.html
Copyright © 2011-2022 走看看