您是否应该将自引用表列设为外键? [英] Should you make a self-referencing table column a foreign key?

查看:15
本文介绍了您是否应该将自引用表列设为外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,要创建类别层次结构,您可以使用列parent_id",它指向同一张表中的另一个类别.

For example to create a hierarchy of categories you use a column 'parent_id', which points to another category in the same table.

这应该是外键吗?有什么缺点/优点?

Should this be a foreign key? What would the dis/advantages be?

推荐答案

是的.确保您没有孤儿(没有父项的条目),并且根据使用情况,如果您定义级联删除,当父项被删除时,其所有子项也将被删除.

Yes. Ensures that you don't have an orphan (entry with no parent), and depending on usage, if you define a cascading delete, when a parent is deleted, all its children will also be deleted.

缺点是会像任何其他外键一样对性能造成轻微影响.

Disadvantage would be a slight performance hit just like any other foreign key.

这篇关于您是否应该将自引用表列设为外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆