如果您有以下架构:
tableA { a, x }
您想将其转换为以下架构:
tableB { id, a }
tableA { id, x } where id has a FK constraint to tableB (id)
您可以使用以下命令序列来执行此操作:
-- sequence to generate the tableB's surrogate key
CREATE SEQUENCE tableB_id_seq;
-- generate tableB
CREATE TABLE tableB AS
SELECT tableB_id_seq.NEXTVAL AS id, a
FROM (SELECT DISTINCT a
FROM tableA);
ALTER TABLE tableB MODIFY (id PRIMARY KEY);
-- add the FK column on tableA
ALTER TABLE tableA ADD (id NUMBER);
-- populate it
UPDATE tableA SET id =
(SELECT tableB.id
FROM tableB
WHERE tableB.a = tableA.a);
-- make it a FK
ALTER TABLE tableA ADD CONSTRAINT afk
FOREIGN KEY (id) REFERENCES tableB (id);
-- drop the old column
ALTER TABLE tableA DROP COLUMN a;