Why VACHAR as Foreign Key might be needed
Imagine that you have two tablesBOOKS & GENRES.You need to have
genre column into your BOOKS which would be one from your GENRESDepending of which data either
genre_id or genre_name u'll keep into your new column, your BOOKS table may
look like one of the following:| id *(pk) | title | author | genre_id *(fk) |
|---|---|---|---|
| 1 | The Little Prince | Saint-Exupéry | 1 |
| 2 | Fear and Loathing in Las Vegas | Hunter Thompson | 2 |
| id *(pk) | title | author | genre_type *(fk) |
|---|---|---|---|
| 1 | The Little Prince | Saint-Exupéry | FICTION |
| 2 | Fear and Loathing in Las Vegas | Hunter Thompson | ALTERNATIVE |
To make it happen we have to make
genre the primary key of our GENRES
and use VARCHAR as foreign key in our BOOKS.| type *(pk) |
|---|
| FICTION |
| ALTERNATIVE |
When you're trying to use VARCHAR as your Foreign Key, you may face with the following exception:
MySQL:ERROR 1215 Cannot add foreign key constraint
No comments:
Post a Comment