MySQL:限制列中的重复次数

标签 mysql duplicates

几个问题如下:

  1. 有没有办法限制特定列中重复项的数量?是否有可用的列属性或设置?

  2. 是否有任何 SQL 查询在导入数据后运行时通过保留该列的前 n 个重复项来删除重复项。

感谢您对此的建议和指导。

最佳答案

1:

也许这不是最好的解决方案,但作为一种选择,您可以使用触发器,如下所示:

create table test (msg varchar(25));

delimiter |
create trigger test_duplicates before insert on test
for each row
begin
  if (select count(*) from test where msg = new.msg) >= 3 then
    signal sqlstate '45000' set message_text = 'You cannot insert 4th duplicate.';
  end if;
end;
|
delimiter ;

它会像这样工作:

mysql> insert into test values ('this is test');
Query OK, 1 row affected (0.03 sec)

mysql> insert into test values ('this is test');
Query OK, 1 row affected (0.03 sec)

mysql> insert into test values ('this is test');
Query OK, 1 row affected (0.02 sec)

mysql> insert into test values ('this is test');
ERROR 1644 (45000): You cannot insert 4th duplicate.
mysql> select * from test;
+--------------+
| msg          |
+--------------+
| this is test |
| this is test |
| this is test |
+--------------+
3 rows in set (0.00 sec)

2:

有目的的导入数据 - 您可以在导入开始时禁用触发器,然后导入所有重复项,然后删除重复项,然后启用触发器,如下所示:

select * from test;
+----------------+
| msg            |
+----------------+
| this is test   |
| this is test   |
| this is test   |
| this is test   |
| this is test 2 |
| this is test 2 |
| this is test 2 |
| this is test 2 |
| this is test 3 |
| this is test 3 |
| this is test 3 |
| this is test 4 |
+----------------+

将重复项放入临时表:

create temporary table tmp like test;
insert into tmp select msg from test group by msg having count(msg) > 3;
select * from tmp;
+----------------+
| msg            |
+----------------+
| this is test   |
| this is test 2 |
+----------------+

现在您可以看到重复项,可以确认并使用临时表中的数据删除它们。

现在您可以启用触发器了。

是的,路很长,可能有点慢,但这是另一种选择!

关于MySQL:限制列中的重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44262915/

相关文章:

mysql - MySQL 中的子查询创建重复结果

mysql - 左外连接和 OR 子句速度很慢。筛选后可以加入吗?

删除重复的 2 列排列

mysql - 根据重复列返回值

php - #1062 - 重复条目

javascript - worklight 从 mysql 获取图像 blob

mysql - 如何根据计数定义范围查询?

mysql - 如何根据MySQL中不同列的值删除重复记录?

mysql - 在 MySQL 中连接表并对列进行求和

linux - 删除重复的 shell 命令