Mysql 增加主键或者修改主键的sql语句操作
程序员文章站
2022-04-14 10:06:23
添加表字段alter table table1 add transactor varchar(10) not null;alter table table1 add id int unsigned n...
添加表字段
alter table table1 add transactor varchar(10) not null; alter table table1 add id int unsigned not null auto_increment primary key
修改某个表的字段类型及指定为空或非空
alter table 表名称 change 字段名称 字段名称 字段类型 [是否允许非空];
alter table 表名称 modify 字段名称 字段类型 [是否允许非空];
alter table 表名称 modify 字段名称 字段类型 [是否允许非空];
修改某个表的字段名称及指定为空或非空
alter table 表名称 change 字段原名称 字段新名称 字段类型 [是否允许非空
删除某一字段
alter table mytable drop 字段 名;
添加唯一键
alter table `test2` add unique ( `userid`)
修改主键
alter table `test2` drop primary key ,add primary key ( `id` )
增加索引
alter table `test2` add index ( `id` ) alter table `category ` modify column `id` int(11) not null auto_increment first ,add primary key (`id`);
修改主键的sql语句块如下
mailbox 表新增字段
drop procedure if exists mailbox_column_update; create procedure mailbox_column_update() begin -- 新增删除标志列 if not exists(select 1 from information_schema.columns where table_schema='cbs' and table_name='mailbox' and column_name='delete_flag') then alter table mailbox add delete_flag int default 2 not null; end if; -- 新增删除日期列 if not exists(select 1 from information_schema.columns where table_schema='cbs' and table_name='mailbox' and column_name='delete_date') then alter table mailbox add delete_date int default 0 not null; end if; -- 如果存在字段account_mail,则修改字段长度 if exists(select 1 from information_schema.columns where table_schema='cbs' and table_name='mailbox' and column_name='email_account') then alter table mailbox modify column email_account varchar(320); end if; -- 如果不存在主键列,则设置双主键 if ((select count(*) from information_schema.key_column_usage where table_schema ='cbs' and table_name='mailbox' and constraint_name ='primary' and (column_name ='email_account' or column_name = 'company_id'))=0)then alter table mailbox add primary key (company_id,email_account); -- 如果只存在一个主键列 elseif ((select count(*) from information_schema.key_column_usage where table_schema ='cbs' and table_name='mailbox' and constraint_name ='primary' and (column_name ='email_account' or column_name = 'company_id'))<2)then alter table mailbox drop primary key,add primary key (company_id,email_account); end if; end; call mailbox_column_update(); drop procedure if exists mailbox_column_update;
补充:mysql 修改主键自增,新增联合主键
alter table `onduty_history` modify column `id` int(11) not null auto_increment first , modify column `name` varchar(50) character set utf8 collate utf8_general_ci not null after `id`, modify column `onduty_date` datetime not null after `name`, add unique key (`id`), add primary key (`name`, `onduty_date`);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
上一篇: 2021网易云音乐怎么领福卡? 网易云福气盲盒找福卡的玩法
下一篇: 我实在是喝不下去了