mysql什么时候需要外键,什么时候在MySQL中使用外键

Is there official guidance or a threshold to indicate when it is best practice to use a foreign key in a MySQL database?

Suppose you created a table for movies. One way to do it is to integrate the producer and director data into the same table. (movieID, movieName, directorName, producerName).

However, suppose most directors and producers have worked on many movies. Would it be best to create two other tables for producers and directors, and use a foreign key in the movie table?

When does it become best practice to do this? When many of the directors and producers are appearing several times in the column? Or is it best practice to employ a foreign key approach at the start? While it seems more efficient to use a foreign key, it also raises the complexity of the database.

So when does the trade off between complexity and normalization become worth it? I'm not sure if there is a threshold or a certain number of cell repetitions that makes it more sensible to use a foreign key.

I'm thinking about a database that will be used by hundreds of users, many concurrently.

Many thanks!

解决方案

there are some official guidelines for this. they're called normal forms, and the practice of putting your database into them is called normalization: http://en.wikipedia.org/wiki/Database_normalization

if you take a db class in college, they'll probably teach you 3nf or bcnf. i've always found those approaches to be a bit heavy-handed, but i have enough experience in db design that i find these questions to be basically intuitive at this point...

in your example, you definitely want to use foreign key constraints. a many-to-one relationship is best expressed that way. it will make selecting movies a bit slower, because you'll have to do a join on the 'people' table and the 'movies' table - possibly many joins depending on how many 'people' fields the movies table has.

but the advantage is that you can easily manage the people themselves. if you want to change the spelling of a person name, you don't have to scan the whole table looking for that person in each field. you can avoid having the same person in the db several times with slight differences in spelling. you can set actions to take if a person is deleted. you can easily count how many different roles a person has had.

don't forget, if you want to use foreign keys, you must make your tables innodb in mysql.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值