在插入之前检查重复的插入语句

2022-01-09 00:00:00 sql duplicates insert mysql

我需要插入,但前提是不存在类似记录
例如:

I need to make a insert but only if similar record don't exists
for example:

INSERT INTO requests ('user_id','subject','text','time') VALUES (56,'test','test 1234',6516516)

INSERT INTO requests ('user_id','subject','text','time') VALUES (56,'test','test 1234',6516516)

但要检查另一条记录中是否有相同的主题"和文本":

but to check if there are same 'subject' and 'text' in another record to:

  1. 不插入任何东西
  2. 更新时间"和用户 ID"

这两种情况我都需要 sql,因为我现在不确定要使用什么.
提前致谢!

I need sql for both cases because I'm no sure at this moment what I'm going to use.
Thanks in advance!

推荐答案

INSERT INTO requests ('user_id','subject','text','time') 
VALUES (56,'test','test 1234',6516516)
ON DUPLICATE KEY UPDATE time = VALUES(time), user_id = VALUES(user_id)

将相关列设置为索引 UNIQUE.

Have the relevant columns set to index UNIQUE.

这将插入一行,但如果主题或文本(或两者)已存在,则改为使用给定的 timeuser_id

This will insert a row, but if subject or text (or both) already exist, you instead update the existing row with given time and user_id

相关文章