I have two tables: users
and cities
.
users cities
------ ------
id(PK) id(PK)
name name
idCity(FK)
and I want to create that foreign key (idCity
) properly. I am using phpmyadmin
so I saw that I had to do:
Create an index on the table in which I want to create the foreign key, in this case,
users
, so I created an index calledidCity
that represents the columnidCity
.I went to the
structure
section and related that index with theid
of the tablecities
.
But I have some doubts in the first step: What index of the five provided should I choose?
After reading MySQL documentation in which I did not clarify my doubts very much, I searched on SO and found this question: Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL? that makes me to clarify a bit more my ideas but I still have some doubts about what I have to choose.
My thoughts of each index type
Primary: Of course I do not have to use it because what I want to achieve it is not a primary key, it is a foreign key.
Index: I could not get a very clear idea of what this index it is but what I could understood on the question of SO that I put above it is: the index may contain rows with identical values in all columns of the index.
As my index represents only the column
idCity
and there could be a lot of users living in the same city, I think this could be the best option.Unique: UNIQUE refers to an index where all rows of the index must be unique. This is the main reason why I have doubts between this one and
INDEX
option. My index only represents one column and I want that the values in that column could be repeated, so I am not secure if I have to use it or not.FULLTEXT and SPATIAL: I have discarded these options because I saw that on
phpmyadmin
I have to create my tables asInnoDB
type and these types of index are supported in other types of table.
My conclusion
I have doubts between UNIQUE
and INDEX
types of index. This is because I do not know if when someone refers to: UNIQUE refers to an index where all rows of the index must be unique, for example, when he is talking about all rows of the index, if it refers that all columns of the table do not have to be the same, that is what I would like to get (it can be more than one user living in a city but not two users repeated).
If it refers that all rows do not have to be the same I think the best approach have to be UNIQUE
because I do not want that two rows will be the same but in the case that it only refers to the index itself (my idCity
column) then I would have to choose INDEX
type of index, because I want that more than one user could live in a city.
My questions
Am I creating my foreign key properly on
phpmyadmin
? I mean, Am I correctly following each step?Which of my conclusions is correct? Or none of them?
Edit: The question that has been provided as possible duplicate answers to my first one question but not to the second one. Please read the full question before mark it as duplicate. Thanks!
Thanks in advance!