mysql 数据库中的唯一列

Unique Column in mysql database

我正面临一个问题,我不相信它可以接受解决方案,所以我希望如果有人知道解决方案,请提出建议。

我的 table 中有一列包含特定记录;其中一些记录是重复的,我想在我的 table 中插入一些新记录,但我希望新记录不要重复。所以,基本上我想控制什么时候可以复制数据,什么时候不能。

我已经试过了,但它不起作用:

ALTER TABLE MyTable DROP PRIMARY KEY

ALTER TABLE MyTable
ADD PRIMARY KEY (`S.No`),
ADD UNIQUE KEY `PCID_uk` (`PCID`),
ADD UNIQUE KEY `USERNAME_uk` (`USERNAME`)

some of those records are duplicated and I want to insert some new records into my table, but I wish for the new records to not be duplicated

约束是为了保证整体的完整性table,所以你要求的不是直截了当的,但仍然是可能的。

我们的想法是创建一个默认值为 1 的新列,然后使用 row_number()(在 MySQL 8.0 中可用)为其提供数据。假设你的 table 的主键是 id,并且你想在列 col 上强制执行部分唯一性,它看起来像:

alter table mytable add col_rn int default 1;

update mytable t
inner join (
    select id, row_number() over(partition by col order by id) rn
    from mytable
) t1 on t1.id = t.id
set t.col_rn = t.rn;

通过手头的设置,您可以创建以下唯一约束

alter table mytable add constraint unique_col_rn unique (col, col_rn);

现在您可以在 table 中插入新记录,不为 col_rn 提供值,因此它默认为 1。如果 col 的记录已经存在,则唯一约束会引发错误。

insert into mytable (col) values (...);