My question is regarding database structuring for a table that links 2 other tables for storing the relationship.
for example, I have 3 tables, users
, locations
, and users_locations
.
users
and locations
table both have an id
column.
users_locations
table has the user_id
and location_id
from the other 2 tables.
how do you define your indexes/constraints on these tables to efficiently answer questions such as what locations does this user have or what users belong to this location?
eg.
select user_id from users_locations where location_id = 5;
or
select location_id from users_locations where user_id = 5;
currently, I do not have a foreign key constraint set, which I assume I should add, but does that automatically speed up the queries or create an index?
I don't think I can create an index on each column since there will be duplicates eg. multiple user_id entries for each location, and vice versa.
Will adding a composite key like PRIMARY_KEY (user_id, location_id)
speed up queries when most queries only have half of the key?
Is there any reason to just set an AUTO INCREMENT PRIMARY_KEY
field on this table when you will never query by that id?
Do I really even need to set a PRIMARY KEY
?