I’m attempting to create two tables with a one-to-many relationship. Here are the schemas for both of them:
CREATE TABLE property_key (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
property VARCHAR(4000)
);
CREATE TABLE property_value (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
prop_key VARCHAR(4000),
prop_value VARCHAR(4000),
lang VARCHAR(2),
INDEX ix_land(lang)
);
When I attempt to add a foreign key relationship between property_value and property_key on prop_key, I get a weird error:
[ALTER - 0 row(s), 0.000 secs] [Error Code: 1005, SQL State: HY000] Can't create table 'test.#sql-a8_6' (errno: 150)
The ALTER syntax I’m using is:
ALTER TABLE property_value ADD CONSTRAINT fk_prop_key FOREIGN KEY (prop_key) REFERENCES property_key(property);
I’ve consulted the MySQL Reference Manual on the matter, but I’ve satisfied all of the requirements there. How do I mitigate this issue?
One issue is that the fields are too large. InnoDB has a field limit of 768 bytes per key, and the foreign key that is being created is around 8KB. Further, it wouldn’t be possible to ensure that the foreign key is unique.
Two options to mitigate this – you can either reduce the size of the VARCHAR fields to less than 768 bytes, or index about the two
idfields instead.