简体   繁体   中英

Which foreign key to use in a many-to-one table

Suppose I have a table Books with columns Book_ID (Primary Key), ISBN (Unique), and several others such as Title/author/etc.

I have another table Sales, with primary key Sale_ID, a foreign key to link to Books, and other fields with info on Sales. Sales only exist for books with ISBNs. Is it better database design to have Book_ID or ISBN be the primary key. Note: I will be LEFT JOINing Sales to Books on whichever the foreign key is chosen.

UPDATE: Some Books have no ISBN's because they're not published with them. However, I don't foresee (at least in the next several years) users being able to sell them, because I have no system for making sure that a given book w/o the ISBN isn't repeated.

我会一直使用你的主键

In general, I think I would go for the surrogate primary key book_id as the foreign key.

There are a few potential issues that I can identify if you were to use the non-primary key ISBN as a foreign key:

  • You might have a missing or unknown ISBN for a particular book. What would you do in case there is a sale of that book?
  • You might have an incorrect ISBN . To edit it, you would have to update all the tables that would be using it as a foreign key.
  • You might want to start selling books that don't have an ISBN in the future. Why are you storing books without an ISBN in the first place?
  • An index on book_id should be much more compact than one on an ISBN field.

I would always use ISBN . This way you have a simple way of enforcing your business rule, "Sales only exist for books with ISBNs" ie by making the ISBN column NOT NULL in the Sales table and referencing the ISBN column in the Books table.

I don't agree with @Daniel Vassallo that because you might want to start selling books that don't have an ISBN in the future you would want to drop the rule in the database today. There is a name for this design flaw: future creep. Also, the considerations of 'compact indexes' should always be secondary to those of basic data integrity.

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