Reputation: 2361
Should foreign keys be numerical ids or can I use other values? 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)?
This would be mostly used for resource/somewhat static tables.
Bonus question: Do I need id fields in join tables? I fail to see their purpose.
Possible? Downsides? Suggestions?
Upvotes: 1
Views: 770
Reputation: 115530
You could have char
or columns with other types used as Foreign Keys. The problem is that your columns would be wider. A TINYINT
, enough to store 256 different statuses, needs 1 byte. A CHAR(10)
, so you can store 'Active'
, 'Suspended'
, etc., needs 10 bytes. 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.
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.
MySQL ENUM
type has several problems, described in the answer by Bill Karwin here: Mysql ENUM type vs join tables
Upvotes: 3
Reputation: 2066
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. They will be integers internally but you can use their names instead. mysql reference
Upvotes: 2