I am developing a HTML5 multiplayer game, where I have a m:n relation between tables “keyword” and “model”, like the following image shows:

keyword.id and model.id are auto_increment unsigned int and keyword.keyword is an unique index.
For the sake of efficiency, I am searching for a way to manage the relation. The trivial way would be:
- Check if keyword already exist
- If yes: update
timesCountandroundCountfrommodel_has_keyword - If no:
insert into keywordandinsert into model_has_keyword
But with a growing number of users playing simultaneously, I’m afraid that the trivial way will become too slow. So what is the most efficient way to do this?
While searching on StackOverflow, I’ve stumpled upon two ideas, but I think they both don’t fit my needs.
INSERT INTO table ON DUPLICATE KEY UPDATE col=val
IfINSERT INTOwould be processed, I would need to trigger anotherINSERT INTOstatement to insert into both tableskeywordandmodel_has_keywordREPLACEstatement: if I replace the record in table keyword,idis assigned the next auto-increment value, so that the reference for tablemodel_has_keywordis lost.
As I’m not an expert, please correct me if I misunderstood something here.
You need to check whether the relation exists, and then insert/update.
A.- Enclose the an INSERT query in a try block, and, in case of error, make an update query. That would save all the checks when the relation doesn’t exists…
B.- Make all INSERT ON DUPLICATE UPDATE. This is gonna do exactly the same as in “A”, but you don’t need to worry about exceptions.
Definitely your second idea is absolutely wrong.
I would not create a table keywords, since you only need the keyword itself… then I would define my model_has_keyword like this:
and update it like this: