I have a table with 4 column (id, name, surname, tel)
id is primary key
name, surname and tel are unique.
Now i have to insert a row and if there is already a row with that name-surname-tel take the id and return it otherwise insert normally.
I thinked at 2 strategy:
1) do a select before insert, if nothing is found insert it otherwise take the id
2) try to insert, if the error code 1 (unique constraint violated) happen do the select and take the id
which one is better? or there is another strategy i can do by php?
You are correct, those are the best options. The differences are minimal if any in terms of performance.
If you do the first one, you still have to implement the second also. Because between your first SELECT
request and your second INSERT
statement, another process could have altered the database, unless you do it in a single transaction.
You could turn it into a SELECT INTO
statement to have the insert/check in a single query, but then you still have to do a second SELECT
to get the ID.
So in conclusion: I would go for the second option where you insert and check for the error.