在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
添加表字段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`); 以上为个人经验,希望能给大家一个参考,也希望大家多多支持极客世界。如有错误或未考虑完全的地方,望不吝赐教。 |
请发表评论