mysql主键sql语句_Mysql增加主键或者修改主键的sql语句操
添加表字段
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 lumns where table_schema='cbs' and table_name='mailbox' and
column_name='delete_flag') then
增加字段的sql语句alter table mailbox add delete_flag int default 2 not null;
end if;
-- 新增删除⽇期列
if not exists(select 1 from lumns 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 lumns 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 colum
n_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`);
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持萬仟⽹。如有错误或未考虑完全的地⽅,望不吝赐教。
如您对本⽂有疑问或者有任何想说的,请点击进⾏留⾔回复,万千⽹友为您解惑!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。