MYSQL 避免两次插入同一行 [英] MYSQL avoid inserting same row twice

查看:45
本文介绍了MYSQL 避免两次插入同一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个涉及 ajax post 请求的系统,该请求将一行插入到表中.好像有时候ajax调用被调用了两次,意思是相同的数据在相邻的两行插入了两次.

I have a system that involves an ajax post request that inserts a row into a table. It seems that sometimes the ajax call is called twice, meaning that the same data is inserted twice in two adjacent rows.

我打算先添加一个查询来尝试选择具有相同数据的行,然后如果行数 = 0 添加它.有没有更好的方法可以避免两次查询?

I'm planning to add a query first to try and select a row with the same data, then if the number of rows = 0 add it. Is there a better way that avoids having to do two queries?

推荐答案

您可以在插入语句中使用 INSERT IGNORE INTO 语法或 INSERT...ON DUPLICATE KEY UPDATE.

You can use the INSERT IGNORE INTO syntax or INSERT...ON DUPLICATE KEY UPDATE on your insert statement.

如果您使用 INSERT IGNORE,那么如果导致重复键,该行实际上不会被插入.但该语句不会产生错误.它会生成警告.

If you use INSERT IGNORE, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead.

INSERT IGNORE INTO mytable
    (primaryKey, field1, field2)
VALUES
    ('abc', 1, 2);

这篇关于MYSQL 避免两次插入同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆