views:

70

answers:

3

Hello.

I'm designing a DB and would like to know the best way to store this:

I have an user table and let's say it can have 100 item slots, and I store an ID. Should I use JSON ({slot1:123232,slot20:123123123,slot82:23123}) or create 100+ fields (slot1, slot2, slotn)?

Thank you.

+1  A: 

With database design normalization, you should not have multivalued attributes.

You might want this.

Users
=====
UserId


UserSlots
=========
UserId
SlotId
Value

Slots
=====
SlotId
Value
Daniel A. White
+3  A: 

Third alternative, create another table for slots, and have a one-to-many relationship between users and slots. Your business logic would enforce the 100 slot limit.

I would recommend against doing the embedded JSON in the database. I'm not sure what DB you are using, but it will likely be very difficult to query the actual slot data for a given user without pulling out and parsing all 100 records.

To create a one-to-many relationship, you'll need a second table

Slots
    id (primary key)
    user_id (mapping to user table)
    item_id (your slot # you want to store)

Now, you can do useful SQL queries like

SELECT * FROM Users,Slots WHERE Slots.user_id = Users.id AND Slots.item_id = 12345

Which would give you a list of all users who have slot item #12345

Matt
A: 

You should not create 100 fields.

Create a table with two fields, the ID and your "JSON Data", which you could store in a string or other field type depending on size.

You could normalize it as others have suggested, by that would increase your save and retrieve time.

Shiraz Bhaiji
I disagree that it will increase the retrieve time. Right now, if he wants any slot data on the user, he has to get all of the slot data on the user, instead of being selective in his SQL query. Not to mention he'd have to parse the JSON as well. And the increased save time will in most likely be non-critical.
Matt
The way I understood it was that he needed to get back the JSON Result. If this were stored in a normalized form, he would have to read 100 rows. If it is stored as a string, he would have to read a single row.
Shiraz Bhaiji