问题
When adding a row to a table, but first checking to see if it exists first Which would be the most efficient way of handling this?
Would it be a case of query to see if it exist, if not then insert.
Or using on duplicate?
Or simply replace (Would this work, if the row did not exist)?
Thanks
回答1:
I think this is the fastest way in MySQL:
REPLACE into table (col1, col2) values(1, 'ABC')
EDIT:
MySQL will delete the row if it does exist and insert a new one.
回答2:
I think you need INSERT IGNORE
see this or INSERT ON DUPLICATE KEY UPDATE
回答3:
depends what you mean by 'exists' if there is a unique field you can check against such as 'email' or 'login' then you can just try the insert and mysql raise error if exists, otherwise you'd do the replace as juergen d just suggested.
NB: don't use replace if you wanted your timestamps for any reason (such as if they're used in encrypted passwords or salt
来源:https://stackoverflow.com/questions/9665301/adding-to-row-in-mysql-if-it-doesnt-exist