我有一个表,我需要在其中的现有列上添加外键。下面是建表:
CREATE TABLE `itemtx` (
`itemTxid` int(11) NOT NULL AUTO_INCREMENT,
`itemcode` varchar(1) NOT NULL,
`weight` decimal(7,3) DEFAULT NULL,
`txtype` varchar(10) DEFAULT 'Pickup',
`tripstopid` int(11) NOT NULL,
`barcode` varchar(25) DEFAULT NULL,
`bagcount` int(11) DEFAULT '1',
PRIMARY KEY (`itemTxid`)
) ENGINE=InnoDB AUTO_INCREMENT=33524 DEFAULT CHARSET=latin1
我需要在 tripstopid 列上添加外键。我不能删除或清空表,因为它包含数据。以下是引用表:
CREATE TABLE `tripstop` (
`tripstopid` int(11) NOT NULL AUTO_INCREMENT,
`tripid` int(11) DEFAULT NULL,
`locationName` varchar(100) DEFAULT NULL,
`userName` varchar(100) DEFAULT NULL,
`locationid` int(11) DEFAULT NULL,
`datetime` varchar(20) DEFAULT NULL,
`createts` varchar(20) DEFAULT NULL,
`latitude` double DEFAULT NULL,
`longitude` double DEFAULT NULL,
`userid` int(11) DEFAULT NULL,
`tid` int(11) DEFAULT NULL,
PRIMARY KEY (`tripstopid`)
) ENGINE=InnoDB AUTO_INCREMENT=4691 DEFAULT CHARSET=latin1
如何在不丢失数据的情况下执行此操作?
最佳答案
您可以通过以下方式实现此目的:
ALTER TABLE itemtx
ADD FOREIGN KEY (tripstopid) REFERENCES tripstop(tripstopid);
通过创建表、向其中插入数据然后更新外键表进行验证,之前输入的数据没有丢失。
关于mysql - 如何使用现有列在表中添加外键而不丢失数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471664/