简体   繁体   中英

Choosing Primary and Foreign Keys

I am having trouble with the concept of primary and foreign keys. My guess is that the model will be my primary key? Not too sure how to connect the rest:/

Product(maker,model, type)

PC(model, speed, ram, hd, price)

Laptop(model, speed, ram, hd, screen, price)

Printer(model, color, type, price)

Generally you want to have a very static, non repetitive, field as your primary key. Usually that ends up being an 'id' column with randomly generated non repeating ids (like UUID for example). It's important to keep in mind your primary key is meant to be the identifier for any given row in the table and there for cannot be repeated by any other row on that same table.

A foreign key is a value in a column who's source is from another table. It's hard to give a solid example with the data you've provided since I'm not sure how the tables and their columns are meant to relate with each other, however lets say the Product table's model field is meant to match the model of an item on the PC table. In this case the model column on Product would have a foreign key relationship to the PC table, meaning that the item stored in the model column on the Product table must match an entry on the PC table, hence the 'foreign' in foreign key.

Generally though you would have the foreign key be a reference to an id rather than an actual field on another table. Like perhaps your product table could have a column named something like 'maker_id' and this would have a foreign key relation to the maker_id on a Maker table. Then on that Maker table you store several columns with information about that maker.

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