Database relationships using phpmyAdmin (composite keys)

我与影子孤独终老i 提交于 2019-12-12 23:32:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2574228/database-relationships-using-phpmyadmin-composite-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!