简体   繁体   中英

Relational database structure - best practice?

Situation: I am a bit of a newbie with databases, and have just plugged MySQLdb into python (at great length). I am looking for basic tips in terms of how to structure my data tables, when to break off into a new table, etc.

Example: Say I'm looking at pet owners, their pets, and their pets' toys. I'm ultimately interested in the properties of the toys.

Pet owner 1: has 3 pets: each pet has 5 toys: each toy has unique properties.
Pet owner 2: has 2 pets: each pet has 4 toys: each toy has unique properties.

Question: Should this stay as one table, or should I have several tables linking owners with pets, then pets with toys, etc.? Is there a hard and fast rule?

Thanks in advance.

I would think of each object as it's own table, then look for one to many relationships and give them their own table, so something like this:

PetOwner

Column
------
OwnerId --primary key
FirstName
LastName
--any other info you want to track on the owner

OwnersPets

Column
------
OwnerId --composite primary key
PetId   --composite primarykey
--any other info relating to the ownership

Pets

Column
------
PetId   --primarykey
PetName
--any other pet properties (color, birthdate, etc...)

PetsToys

Column
------
PetId  --composite primary key
ToyId  --composite primarykey
--any other info relating to the pets ownership of the toy (dateOfIntroduction maybe)

Toys

Column
------
ToyId--primarykey
Manufacturer
Type
Cost
DateOfPurchase
--any other toy properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM