Category Archives: Database

关于外键的使用

这几天在调整前辈设计的数据库,大概11张表,都是只用了主建没有任何关联,本来以为这是一个很明显的错误,但是在网上搜索了一下,发现貌似更多人支持不用外建。理由大多数是影响速度,可以在逻辑层做数据检测,MySQL常用的MyISAM本身也不支持外建。支持的理由是数据统一性和ER图的可读性增加。

后来在GOOGLE到了两个比较用用的文章,一个是有人在Stackoverflow提的问题Are foreign keys really necessary in a database design,另一个是Curtis Poe在Technical写的Misunderstanding Foreign Keys

While the author is specifically referring to foreign keys not being needed for Rails, the problem is more widespread. I’ve listened to people tell me that they prefer to handle data integrity code at the app level rather than the database level. Certainly there are times where this is more appropriate, but not for something as basic as foreign keys. Concluding that foreign keys are not necessary is very dangerous and short-sighted.

First, keep in mind that a database like MySQL or PostgreSQL is effectively a programming platform with a declarative language (SQL) sitting on top of it. If you have an SQL statement inserting data, you want the receiving table to have the data validation in the form of foreign keys, custom data types, enums, triggers and so on. If you’re writing code for personal use or you control an open-source project, skip this if you want. It’s your code; it’s your choice. However, if you’re writing code for a business, you don’t know who will be maintaining it tomorrow. Maybe they don’t know about your clever data validation routines which allow you to forego foreign keys. Maybe they’re finding your code too slow so they decide to write directly to the database themselves. Whatever the reason, by putting the data validation as close as possible to the data munging, you make it harder to circumvent.

总的来说还是必不可少的,等做好foeign keys把表贴上来。