mysql - MSQL 唯一约束检查仅向前插入记录 不存在的记录
问题描述
该表已经有重复条目。我想在 MQSL DB 中创建一个唯一约束而不删除现有的重复项。如果以后出现任何重复条目,则会显示错误。鉴于打击查询在 MYSQL 中不起作用。
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id >10000;
or
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id <> (343,34534,34534)
我们在 SQL 中有类似的解决方案吗?
解决方案
Add an additional column to the table that indicates the existing values.
Set it to NULL
for the existing values. And give it a constant value, say 1
, for the new rows. Then create a unique index or constraint on this column:
alter table t add constraint unique (employee_id, is_old)
Actually, I realize that you probably don't want duplicates with singleton old values and new values. That is just an issue of setting the value to NULL
only for duplicates in the history. So, one row would have a constant value (say 1
) in the historical data.
MySQL allows duplicate values on NULL
, which is why this works.
推荐阅读
- docker - Docker-compose - 在单个主机上 -scale 的目的是什么?
- python - Pandas Groupby CumSum 仅在连续行上
- python - 在 DRF 中创建对象和子对象
- python - jupyter notebook ipywidgets 未显示(无错误)
- skypedeveloper - 如何使用Skype SDK通过用户提供的URI加入会议
- python - 合并两个列表(偶数/奇数元素)
- shell - 从 Kubernetes 部署对象中提取特定的 args 值
- excel - VBA Excel 到 VBA 书签 - 保留书签
- arrays - 使用 sas 将一组日期与另一组日期进行比较
- google-apps-script - Google Calendar API - 无法使用 eventNamedHangout 创建 Google Hangout 链接