1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you helped a lot and I could managed to get it working with making both fields as INT(4) types. What if I want to use multiple values from another_table? (MALE and FEMALE values in same row.) I couldn't change the type as SET after my initial setup :(
@noway: The you would use another table to connect the two tables. You can add a unique constraint to that table, to prevent one record in mytable having more than one of each of the values from the another_table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.