首页 > 解决方案 > 插入mysql表时如何避免基于特定键的重复记录

问题描述

我有一个带有这些键的表(TableA)-> user_id,content_id,points,content_type,description,created_date

content_id 是我的文档的唯一 id,因此每个 content_id 可以有 2 条 content_type(1-> like 和 2 -> share)的记录。

现在我想避免根据 content_id、content_type将重复记录插入TableA

我需要这样:(在此表中没有重复记录)

:id user_id, content_id, points, content_type, description, created_date: 
1    1        1a1           5        1              null     2021-02-26 08:26:54
2    1        1a1           5        2              null     2021-02-26 08:26:56
3    1        1a2           5        1              null     2021-02-26 08:26:54
4    1        1a3           5        2              null     2021-02-26 08:26:56

****我不需要像这样:****(在这个表中有重复的记录(第一个和第二个ID))

:id user_id, content_id, points, content_type, description, created_date: 
1    1        1a1           5        1              null     2021-02-26 08:26:54
2    1        1a1           5        1              null     2021-02-26 08:26:56
3    1        1a1           5        2              null     2021-02-26 08:26:56
4    1        1a2           5        1              null     2021-02-26 08:26:54
5    1        1a3           5        2              null     2021-02-26 08:26:56

标签: mysqlsql

解决方案


你想要的是 , 和 的组合user_idcontent_id独一无二content_type的。
所以创建一个复合PRIMARY KEY

CREATE TABLE TableA(
  user_id INTEGER, 
  content_id VARCHAR(10), 
  points  INTEGER, 
  content_type INTEGER, 
  description VARCHAR(100), 
  created_date DATETIME,
  PRIMARY KEY(user_id, content_id, content_type)
)

推荐阅读