Adding to row in MySQL if it doesn't exist

☆樱花仙子☆ 提交于 2021-02-19 06:22:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!