[英]Changing keys and foreign keys
I have two tables. 我有两张桌子。 First one is dogs:
第一个是狗:
oldId name
----- -----
'AX01' Fido
'AX02' Pluto
... ....
and another called serviced: 另一个称为服务式:
Id ServicedDog Descripton
--- ------------ ----------
1 'AX01' 'Dog bath'
2 'AX01' 'Dog Vaccined'
...
22 'AX02' 'Dog bath'
...
The problem we have is that we need to convert the oldId column (CHAR(4)) of table dogs to an auto incremented INT one and update the respective ServicedDog column of table serviced to have the new values (it is a foreign key). 我们遇到的问题是,我们需要将表狗的oldId列(CHAR(4))转换为自动递增的INT 1,并更新服务的表的相应ServicedDog列以具有新值(它是外键)。 Another of the problems I have is the data type for ServicedDog is CHAR(4) and I will need to change the data type of this column to INT.
我遇到的另一个问题是ServicedDog的数据类型是CHAR(4),我将需要将此列的数据类型更改为INT。 Please, tell me, how can this be done?.
请告诉我,这怎么办? Thanks
谢谢
(Without seeing SHOW CREATE TABLE
for what you have, I am making some guesses.) (在没有看到
SHOW CREATE TABLE
的情况下,我正在做出一些猜测。)
Is it really called oldid
now? 现在真的叫
oldid
吗?
-- Add the desired id (and populate it);
-- Replace the existing PK:
ALTER TABLE dogs
ADD COLUMN id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL,
DROP PRIMARY KEY,
ADD PRIMARY KEY(id)
ADD INDEX(oldid);
-- add new dog_id (but do not populate)
ALTER TABLE serviced
ADD COLUMN dog_id SMALLINT UNSIGNED NOT NULL,
ADD INDEX(dog_id);
-- establish new linkage:
UPDATE serviced
JOIN dogs ON serviced.oldid = dogs.oldid
SET serviced.dog_id = dogs.id;
Notes: 笔记:
oldid
is really the current name of that column. oldid
实际上是该列的当前名称。 SMALLINT UNSIGNED
); SMALLINT UNSIGNED
); change the declaration if you might have more. oldid
-- for the conversion; oldid
上保留索引-用于转换; you may want to drop the index and maybe even the column.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.