views:

468

answers:

1

Hi,

I am bit confused on making a good relational database. I am using phpmyAdmin to create a database. I have the following four tables. Don't worry about that fact place and price are optional they just are.

  1. Person (Mandatory)
  2. Item (Mandatory)
  3. Place (Optional)
  4. Price (Optional)

Item is the main table. It will always have person linked. * I know you do joins in mysql for the tables. If I want to link the tables together I could use composite keys (using the ids from each table), however is this the most correct way to link the tables? It also means item will have 5 ids including its own. This all cause null values (apparently a big no no, which I can understand) because if place and price are optional and are not used on one entry to the items table I will have a null value there. Please help!

Thanks in advance. I hope this makes sense.

+2  A: 

NULL values

It also means item will have 5 ids including its own. This all cause null values (apparently a big no no, which I can understand) because if place and price are optional and are not used on one entry to the items table I will have a null value there

Personally I think this is one situation where NULL values are perfect, and I certainly wouldn't have any doubts about putting this into my database design.

One way I've seen others achieve the same thing without NULL values is to create a record in the optional tables (place and price in your example) with an ID of 0 that signifies there's no related record - but this just makes 10 times more work for the developer of the application to filter these records out - it's FAR easier to do a join and if you don't get any records back, there are no related records in the optional table.

Just remember to do a LEFT or RIGHT OUTER join if you want to return Items regardless of whether they have a Place or Price associated (you'll get NULL values in the optional table columns for Items that don't have associated records) and an INNER join if you only want the Items that do have an associated optional record.

Composite Keys

A composite key is a key in a table that's made up of more than one column. If each of your Person, Item, Place and Price all have an ID (even if it's just an auto-incrementing number) you won't need a composite key - just a primary key column in each table, and a foreign key column in the Item table for each related table - e.g. item_id, person_id, place_id, price_id. You state that Item has its own ID, so you shouldn't need a composite key - just a primary key on the item_id column.

Andy Shellam
How would you make sure the correct ids get filled in on INSERT? For example when I insert I don't get the correct id's for the other tables would I need to do this with mysql statements?
Cool Hand Luke UK