Suppose this is the SQL code of the table:
CREATE TABLE `user_is_in` (
`id_user` INT NULL ,
`id_city` INT NULL ,
`when` DATETIME NULL ,
INDEX `fk_user` (`id_user` ASC) ,
INDEX `fk_city` (`id_city` ASC) ,
CONSTRAINT `fk_user`
FOREIGN KEY (`id_user` )
REFERENCES `user` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_city`
FOREIGN KEY (`id_city` )
REFERENCES `city` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
The use of the table is to store kind of Foursquare checkins (A user was registered on one place at one time).
Now I have 2 options:
-
Create an unique index with the 3 fields and no primary key:
UNIQUE INDEX
id_user_is_in_UNIQUE(id_userASC,id_cityASC,whenASC) -
Create an additional classic id autoincrement field
I don’t like the 2nd option because I want to create queries over users and cities (i.e.: search all users who made a checkin in a city on one date)
Thanks in advance.
You should do both. Add an auto-incrementing primary key and add a uniqueness constraint against all three columns. With a separate system assigned keys you make it easier to define foreign keys to this new table, if and when eventually required. And having the uniqueness constraint against all three columns will ensure that duplicate data is not created.
Some quick side notes:
NOT NULL.association table.