我的一個客戶有一個動態變化的商業模式,他們賣的根據 日常美元匯率的產品,這意味着產品的價格變化每天都在 和客戶仍希望保留銷售產品的歷史(價格,date_sold)(此信息保存在訂單表)。怎麼辦行版本在MySQL中,同時保持外鍵參考完整性
唯一的方式我能想到的實施爲我的客戶的解決方案是通過使用行版本。 (他們使用MySQL作爲數據庫服務器)
這是當前模式(就像原型),我想要實現,同時保持引用完整性,但是當我創建訂單表我得到一個錯誤如下:
ERROR 1005 (HY000): Can't create table 'mydb.orders' (errno: 150)
。由此架構設計:
create table products (
id int not null auto_increment,
prod_id int not null,
name varchar(200) NOT NULL,
price decimal(8,2) NOT NULL default 0,
is_active boolean default 0,
deleted boolean default 0,
create_date timestamp NOT NULL default current_timestamp,
end_date timestamp NOT NULL default '2030-01-01 00:00:00',
primary key(id)
)engine=innodb;
create table orders (
id int not null auto_increment,
prod_id int not null,
foreign key(prod_id) references products(prod_id),
date_sold timestamp NOT NULL default current_timestamp,
primary key(id)
)engine=innodb;
爲什麼我不能創建一個外鍵的產品表?我究竟做錯了什麼?
任何意見大加讚賞,
謝謝!
FYI
處理版本在我db_layer數據庫服務器安裝
- 的Percona的MySQL 5.5.27
- 我使用時間戳和布爾標誌
UPDATE: 我不得不創建訂單(PROD_ID)列的索引,對於訂單表中的正確架構定義 是:
create table orders (
id int not null auto_increment,
prod_id int not null,
index product_id(prod_id),
foreign key(prod_id) references products(prod_id),
date_sold timestamp NOT NULL default current_timestamp,
primary key(id)
)engine=innodb;
注意你存儲的其他所有產品信息(姓名等)的副本,只是有價格的副本。將價格拆分到另一個表格(使用日期),或者在有人更新product.price時使用觸發器將舊價格寫入歷史表格。 –