我有以下2个表格。他们都有数据。我想将charge_date从日期修改为日期时间。 Mysql不允许我这样做。 我想这样做而不会删除并重新创建现有表格。
CREATE TABLE `cmpny_charges` (
`company_id` int(10) unsigned NOT NULL,
`charge_id` varchar(45) NOT NULL,
`charge_date` date NOT NULL,
`charge_amt` double NOT NULL,
`chargeholder_id` varchar(20) NOT NULL,
`filing_no` int(10) unsigned DEFAULT NULL,
`registration_date` date DEFAULT NULL,
`srn` varchar(10) DEFAULT NULL,
`charge_type` char(1) NOT NULL,
`updated_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created_ts` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`doc_no` varchar(45) DEFAULT NULL,
PRIMARY KEY (`company_id`,`charge_id`,`charge_date`),
KEY `cmpny_charges_FK_2` (`chargeholder_id`),
KEY `cmpny_charges_FK_1` (`filing_no`),
CONSTRAINT `cmpny_charges_FK_2` FOREIGN KEY (`chargeholder_id`) REFERENCES `chargeholder_dtls` (`chargeholder_id`),
CONSTRAINT `cmpny_charges_FK_3` FOREIGN KEY (`company_id`) REFERENCES `company` (`company_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `cmpny_charge_dtls` (
`company_id` int(10) unsigned NOT NULL,
`charge_id` varchar(45) NOT NULL,
`charge_date` date NOT NULL,
`modification_part` text,
`part_property_charged` text,
`filing_date` datetime DEFAULT NULL,
`srn` varchar(9) DEFAULT NULL,
`rate_of_interest` text,
`repayment_terms` text,
`margin` text,
`nature_instrument` text,
PRIMARY KEY (`company_id`,`charge_id`,`charge_date`),
CONSTRAINT `FK_cmpny_charge_dtls_1` FOREIGN KEY (`company_id`, `charge_id`, `charge_date`) REFERENCES `cmpny_charges` (`company_id`, `charge_id`, `charge_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
这是我想要执行的更改脚本
set foreign_key_checks=0;
lock tables cmpny_charges write, cmpny_charge_dtls write;
ALTER TABLE `cmpny_charge_dtls` CHANGE `charge_date` `charge_date` datetime not null;
ALTER TABLE `cmpny_charges` CHANGE `charge_date` `charge_date` datetime not null;
unlock tables ;
set foreign_key_checks =1;
执行show engine innodb status
时出现如下错误最新的外键错误
140313 19:54:03表的外键约束出错 csmart / cmpny_charge_dtls:引用表中没有索引 将包含列作为第一列或数据类型 引用的表与表中的表不匹配。约束:,
CONSTRAINT" FK_cmpny_charge_dtls_1"外键(" company_id", " charge_id"," charge_date")REFERENCES" cmpny_charges" (" COMPANY_ID&#34 ;, " charge_id"," charge_date")表中外键中的索引是 " PRIMARY"看到 http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html 用于正确的外键定义。 InnoDB:重命名表csmart
。至csmart
。cmpny_charges
失败了!
这些是警告
我不知道暂时删除它们的约束名称。不同名称可以存在相同的约束。 (我需要更新此数据库的多个副本)
我想这样做而不创建临时表,在那里复制数据然后将它们重命名为原始表。当多个会话登录到同一数据库时尝试同时执行相同的操作而使其处于不一致状态时,这会导致问题。
答案 0 :(得分:0)
添加新列,将数据复制到其中。然后修改外键以指向新列,并删除旧列。
alter table cmpny_charges add charge_date2 datetime;
update cmpny_charges set charge_date2= charge_date;
-- (I am used to do this via GUI, sorry...)
-- drop foreing key
---modify the primary key
-- recreate the foreing key
alter table cmpny_charges drop charge_date;