mysql - 插入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
解决方案
你想要的是 , 和 的组合user_id
是content_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)
)
推荐阅读
- r - 在带有空格的列中读取 na -R
- flutter - 使用 Flutter 创建自定义的 SliverPersistentHeader,例如 Widget
- javascript - 当 LocalStorage 为空时使按钮无效
- java - settext后的Android edittext光标错误
- server - 尝试发送消息以服务 Ubuntu 18.04 LTS 时出错
- python - 为什么井字棋 minimax 不能正常工作
- sql-server - 如何在 Docker 上的 SQL Server 中从数据库备份中查看 .bak 文件
- django - Annotate 中的 Django Sum
- javascript - 在对象 React/Javascript 中映射数组
- kotlin - 在 EventHandler 中更改观察到的属性值会更改事件属性