[英]Migrate association column in PSQL
我有一個表,我們遇到了問題,因為我們錯誤地假設表A與表B相關聯,但應該是表C。現在我們要添加功能只是一個問題,但我不確定如何正確遷移它。
我能形容的最好方法是說您有一個account
, vehicle
, vehicle
vehicleHistory
, carLot
。
當前vehicleHistory
與vehicle
但實際上vehicleHistory
應該與carLot
。 示例表。 這是今天的表格:
帳戶
id |
-----
001 |
002 |
003 |
車輛
id | accountId
----------------
101 | 001
102 | 002
103 | 003
車輛歷史
id | vehicleId
----------------
201 | 101
202 | 102
203 | 103
車票
id | accountId
----------------
301 | 001
302 | 002
303 | 003
但是應該是這樣的:
帳戶
id |
-----
001 |
002 |
003 |
車輛
id | accountId
----------------
101 | 001
102 | 002
103 | 003
車輛歷史
id | carLotId
---------------
201 | 301
202 | 302
203 | 303
車票
id | accountId
----------------
301 | 001
302 | 002
303 | 003
這是我什至應該在PSQL中嘗試的東西,還是只應使用應用程序的語言(Node或Scala)編寫腳本?
我會在數據庫中非常仔細地處理此問題,但我認為可以做到。 基本上,您希望將VehicleHistory
替換為:
select vh.id, cl.carlotid
from VehicleHistory vh left join
Vehicle v
on vh.vehicleid = v.id left join
CarLot cl
on v.accountid = cl.accountid;
我的建議是:
VehicleHistory
表。 查看是否有任何中斷。 要填充新列:
update VehicleHistory
set CarLotId = t.CarLotId
from <temporary table based on above query> t
where t.id = VehicleHistory.id;
根據您的描述,應該沒有理由刪除原始列。
-- to be safe: make a copy
CREATE TABLE vehicle_history_saved AS select * from vehicle_history;
-- (maybe drop FK constraints here)
-- do the update
UPDATE vehicle_history dst
SET vehicle_id = cl.carlot_id
FROM carlot cl
JOIN vehicle ve ON ve.account_id = cl.account_id
WHERE dst.vehicle_id = ve.id
;
ALTER TABLE vehicle_history RENAME vehicle_id TO carlot_id;
-- (maybe recreate FK constraints here)
-- (maybe drop copy )
-- DROP TABLE vehicle_history_saved;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.