问题
I got 2 tables User and Company. These two have a inventory.
DataTables
Item
ItemId | Name
================
1 | Glass
4 | Wood
User
UId | Name
============
1 | Max
Company
CId | Name
==================
1 | EvilCorp
Inventory
RowId | UId | CId | ItemId | amount
=================================================
1 | 2 | Null | 4 | 10
2 | 23 | Null | 4 | 5
3 | Null | 1 | 1 | 7
4 | Null | 1 | 4 | 70
Let say I have 500 users and 300 companys and every one has 20 inventory slots, I will have 16000 null values in my Inventory table (6000 UId nulls + 10000 CId nulls).
I want a SQL query that will say this information.
Result
Owner | Item | Amount
===========================
MAX | Wood | 10
EvilCorp | Glass | 7
EvilCorp | Wood | 40
My problem is that my Inventory table is bad due to all the nulls that will appears against CId when the record is for a User, and vice versa.
Do you know how to create a good table, without huge or/and complex SQL queries?
回答1:
You have Users, Companies and Owners. Users and Companies are Owners.
This is a common situation that can be put into tables various ways.
Every table holds the rows that make some statement true:
// "user [OId] has ..."
User(OId,...)
fk OId references Owner -- a user is an owner
// "company [OId] has ..."
Company(OId,....)
fk OId references Owner -- a company is an owner
// "Owner [OId] has ..."
Owner(OId,...)
// "[OId] owns [n] of item [itemId]"
Inventory(Oid,ItemId,amount)
fk OId references Owner
fk ItemId references Item
This comes from choosing tables that make plain statements about parts of your application. For variations read about subtables and supertables for subtypes and supertypes. See this answer or this one.
来源:https://stackoverflow.com/questions/24418273/inventory-database-design