I've been looking over some sample schemas, and here's something I've seen done several times, but being new to MySQL I'm not sure why. Say I've got a table for items:
CREATE TABLE item (
itemID CHAR(5) NOT NULL,
name VARCHAR(255) NOT NULL,
itemType VARCHAR(255) NOT NULL,
PRIMARY KEY (itemID),
CONSTRAINT fk_item_itemType FOREIGN KEY (itemType) REFERENCES itemType(name)
) ENGINE = MyISAM;
Why would you need itemType
to be a foreign key to another table that lists all the possible item types? Would it prevent typos if the entered value wasn't in the other table? The other table is this:
CREATE TABLE itemType (
name VARCHAR(255) NOT NULL,
PRIMARY KEY (name),
) ENGINE = MyISAM;
INSERT INTO itemType (name) VALUES ('gloves');
INSERT INTO itemType (name) VALUES ('boots');
INSERT INTO itemType (name) VALUES ('ring');
Best Answer
It seems the idea here is to restrict what
itemType
s can be used in theitem
table to only those in theitemType
table, while at the same time avoiding having to do a JOIN with theitemType
table to get the actual value whenever youSELECT
from the item table. It's a kind of denormalization in order to optimizeSELECT
statements. This comes at a cost of needing more storage space since everyitem
record will have the fullitemType
name, potentially as long as 255 characters.With a normalized approach you would have tables defined like this:
However, when
SELECT
ing from theitem
table you would now have to do aJOIN
in order to display the itemType:Another solution to this is using an ENUM and avoid the
itemType
table altogether:The drawback of this approach is that you would have to
ALTER
the table whenever you want to add a newitemType
.