简体   繁体   English

MySQL外键使用id或值?

[英]MySQL foreign key use id or value?

Should foreign keys be numerical ids or can I use other values? 外键应该是数字ID还是可以使用其他值? I currently use ids but I have to keep joining/querying tables to translate values to ids before validating, inserting, etc. (Aside from input, I also reference values instead of ids in my code) For example, say I have a status table -- can I do away with the numerical ids and just keep the values ('active', 'suspended', etc)? 我目前使用id,但是在验证,插入等之前,我必须保持联接/查询表将值转换为id的功能。(除了输入,我还在代码中引用了值而不是id)例如,说我有一个status表-我可以取消数字编号,而只保留值(“活动”,“暂停”等)吗?

This would be mostly used for resource/somewhat static tables. 这将主要用于资源/某种程度上的静态表。

Bonus question: Do I need id fields in join tables? 奖励问题:我是否需要联接表中的id字段? I fail to see their purpose. 我看不到他们的目的。

Possible? 可能? Downsides? 缺点? Suggestions? 有什么建议吗?

You could have char or columns with other types used as Foreign Keys. 您可以将char或具有其他类型的列用作外键。 The problem is that your columns would be wider. 问题是您的列会更宽。 A TINYINT , enough to store 256 different statuses, needs 1 byte. TINYINT足以存储256个不同的状态,需要1个字节。 A CHAR(10) , so you can store 'Active' , 'Suspended' , etc., needs 10 bytes. 一个CHAR(10) ,因此您可以存储'Active''Suspended'等,需要10个字节。 Not only the rows will be wider but the indexes, too. 不仅行将更宽,索引也将更宽。 And space may not be a problem with modern hard disks but index size affects efficiency, too. 空间对于现代硬盘而言可能不是问题,但是索引大小也会影响效率。

So, yes, you could do away with the numerical ids and just keep the values only, if you can tolerate the performance degradation. 因此,是的,如果可以容忍性能下降,则可以取消数字ID,而仅保留值。

Alternatively, you could use CHAR(1) as the Primary Key of the status table (and off course as Foreign Key in other tables), so you can have 'A' , for 'Active' , 'S' for 'Suspended' , etc. It works if you don't have more than 26 different statuses. 或者,您可以将CHAR(1)用作status表的主键(当然,在其他表中也用作外键),因此对于'Active'可以使用'A' ,对于'Suspended' 'S' 。等等。如果您的状态不超过26种,则可以使用。

MySQL ENUM type has several problems, described in the answer by Bill Karwin here: Mysql ENUM type vs join tables MySQL ENUM类型有几个问题,请参见Bill Karwin的回答: Mysql ENUM类型vs联接

Foreign keys can reference other kinds of columns as well. 外键也可以引用其他类型的列。

enum is recommended if you have a few different strings you want to use efficiently. 如果您想使用几个不同的字符串,建议使用enum They will be integers internally but you can use their names instead. 它们在内部是整数,但是您可以改用它们的名称。 mysql reference mysql参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM