Question

A client of mine has a dynamic changing business model, they sell products according to the daily USD exchange rate, this means the pricing of products change on a daily basis and the client still wants to retain the history (price, date_sold) of sold products (this info is saved in the orders table).

The only of way I can think of implementing a solution for my client is by using row versioning. (They are using MySQL as database server)

This is the current schema (just as prototype) that I want to implement while maintaining referential integrity, however when I create the orders table I get an error as follows :

ERROR 1005 (HY000): Can't create table 'mydb.orders' (errno: 150)

Herewith the schema design :

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;

Why am I not able to create a foreign key to the products table? What am I doing wrong?

Any advice much appreciated,

Thanks!

FYI

Database Server setup

  • Percona MySQL 5.5.27
  • I handle versioning in my db_layer by using the timestamps and boolean flags

UPDATE : I had to create an index on the orders(prod_id) column, the correct schema definition for the orders table is :

 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;
Was it helpful?

Solution

There needs to be an index on the column you are referencing. Try creating an index on prod_id in the products table, then try creating your foreign key.

Also, why not just add a price column to the order table and copy the current product price there at the time of the sale. That will provide your history and you won't need to maintain different versions of the product records.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top