原博文:https://blog.csdn.net/qq_35211818/article/details/79709657
添加表字段
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;