简体   繁体   English

如何使列值唯一组合?

[英]How to make unique combination of columns values?

I have a table with data like this: 我有一个数据表,如下所示:

id |  link  |  name  | date 
 1     aa      bob      1
 1     aa      tom      2
 1     bb      tom      3
 2     cc      lora     4

It means I can have not unique values in any column but I CAN'T have the same row with identical id link name (date doesn't matter). 这意味着我在任何列中都不能有唯一值,但我不能在同一行中使用相同的id link name (日期无关紧要)。 This is the example what I can't have: 这是我无法拥有的示例:

 id |  link  |  name  |  date 
  1     aa       bob      1
  1     aa       bob      2

I tried to: 我试过了:

ALTER TABLE table ADD UNIQUE KEY `uk_id_link_name` (id, link, name);

also: 也:

ALTER TABLE `table` ADD UNIQUE `unique_index`(`id`, `link`, `name`);

But it gives me an error: 但这给了我一个错误:

Duplicate entry 双重输入

How to make unique rows (combination of columns values which is not unique)? 如何制作唯一的行(不唯一的列值组合)?

EDIT: I don't want to delete duplicates from table. 编辑:我不想从表中删除重复项。

Your table already violates the unique constraint. 您的表已违反唯一约束。 So you need to get rid of the offending values. 因此,您需要摆脱有问题的值。

You can delete all but the earliest date: 您可以删除除最早日期以外的所有日期:

delete t
    from t join
         (select id, link, name, min(date) as mindate
          from t
          group by id, link, name
         ) tt
         using (id, link, name)
    where date > mindate;

When the data is compatible, you can add the unique constraint. 当数据兼容时,可以添加唯一约束。

Note: back up/make a copy of the table before doing this, so you don't lose data that you might really need. 注意:在执行此操作之前,请备份/制作表的副本,这样就不会丢失您真正需要的数据。

The correct syntax for SQL Server should be the next: SQL Server的正确语法应为下一个:

ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE (id, link, name)

But before create the constraint, of course you should ensure that there are not existing rows braking the constraint, for example using this query: 但是,在创建约束之前,您当然应该确保没有现有的行约束约束,例如使用以下查询:

SELECT id, link, name, COUNT(*)
FROM TableName
GROUP BY id, link, name
HAVING COUNT(*) >= 2

This query returns the duplicates grouping by the three fields: id, link, name 该查询按三个字段返回重复项分组:id,链接,名称

If the query returns rows, you have to solve these duplicates before create the unique constraint. 如果查询返回行,则必须在创建唯一约束之前解决这些重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM