noway
noway

Reputation: 2585

Using values from another table as ENUM values in a table

Let's assume that I have mytable in mySQL

CREATE TABLE `mytable` (
  `gender` enum('MALE','FEMALE','UNISEX') NOT NULL,
);

I don't want to enumerate these values at design time. I want to put them in another_table as values.

In another_table the SELECT values are:

ID    NAME
==    ======
01    MALE
02    FEMALE
03    UNISEX

I can define the mytable.gender as INT and combine these two tables in WHERE clause with sth like mytable.gender=another_table.id.

Can I create a database level foreign-key relationship with these enum values at design time?

Upvotes: 1

Views: 1871

Answers (1)

Guffa
Guffa

Reputation: 700372

Yes, you use a foreign key constraint.

That will make the database refuse inserts or updates to id values in the mytable table that doesn't exist in the another_table table, and refuse deletes from the another_table table for values that are used in the mytable table.

Upvotes: 2

Related Questions