Let’s say I am programming a MMORPG. I modeled a Entity character that can have a multitude of attributes like coating, strength, color and so on. Because I do not know these attributes in advance (what and how many of them), I thought I create an extra table for it, like so:
CREATE TABLE character (INTEGER id, VARCHAR name, INTEGER player_id);
and
CREATE TABLE attributes (INTEGER character_id, VARCHAR key, VARCHAR value);
I would then be able to introduce a multitude of new attributes. However, how would I query this construct?
The query
SELECT * FROM character JOIN attributes ON character.id=attributes.character_id;
will obvioulsy only work for a single attribute. Do I have to JOIN the attributes table more than once or is there another solution?
Is there a way to have different types for the attribute.value Part? Doing it the way I am doing now would limit me to a VARCHAR representation.
Another possibility is to use hstore instead of EAV model.
That way you can store the attributes as a map (key – value).
Hope this helps.
UPDATE
I made a small benchmark to compare hstore vs two tables.
And I’ve got the following results:
And using hstore: