I am working on a project where I want the category "Items" to have sub entities in MySQL.

In my situation the main entity is called "Items", however I need to divide them in to smaller portions such as:

  • Consumables
  • Drugs
  • Gear/tools
  • Armor
  • Ranged weapons
  • Melee weapons.

Those sub entities also needs some sub entities as well. For example ranged weapons need the sub entities:

  • Flame weapons
  • Primitive weapons
  • Launchers
  • Grenades
  • Exotic weapons

I have tried to search it but can't seem to find any solution for it. How do I design these entities?

Also when I do a simple SELECT * FROM item; will it then show ALL the items that are in all the sub categories?

Or will it only show those which have been inserted directly in the item entity?

有帮助吗?

解决方案

There are a few ways this can be handled.

One, create an items table with relevant IDs associated with each row.

For instance,

id,type,category,subcategory 
1, item, NULL, NULL
2, item, Consumables, NULL
3, item, Drugs, NULL
.
.
.
x, item, Ranged Weapons, NULL,
.
.
.
y,item, Ranged Weapons, Flame weapons
z,item, Ranged Weapons, Primitive weapons

Although this table would be very easy to query, it's also very difficult to maintain. Also, if you don't store ids and instead store the text values, it'll get big fast (and be even more difficult to maintain)

Now, another option is to use a tree structure. Doing this, you might try creating an items table like the following:

id,name,level,parent_id
0, Items,0,NULL
1,Consumables,1,0
2,Drugs,1,0
.
.
.
x,Ranged weapons,1,0
.
.
.
y,Flame weapons,2,x
z,Primitive weapons,2,x

Under this table, you could query items WHERE parent_id = x (other words, ranged weapons). You may need to nest your queries a bit, depending on how many levels you have. But the logic is usually fairly straightforward.

If I had only a few levels, like you're describing (a few meaning not 10 or 20 or 100), then no question I'd do a tree structure like the second example. If you do have multiple levels, you'll need to think about the actual queries you'll be running against it and maybe look into various normal forms (http://en.wikipedia.org/wiki/Database_normalization) to represent your data.

Again, though, with only a few levels,I'd tree structure this thing in a heartbeat. It'll be easier to maintain and, as long as you don't end up having to climb several levels up the tree, you shouldn't have any problems with performance (assuming good indices, good queries, etc)

Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top