日常,理想的情况下,应该是数据库设计的时候都会增加唯一索引,或者联合索引来保证数据的唯一性;
但是在一些特殊情况下,前期的设计缺陷,就会留下很多技术债,导致后期难以维护;
最近遇到数据重复问题,表里面没有添加唯一索引控制数据的唯一性,在并发的情况下,导致数据可重复插入;
数据库内的数据有小部分数据已经是重复了的,现在是添加不了唯一索引了,只能在每天数据插入的时候先查询然后再插入;
mysql 关键字 dual 虚拟表:
dual: mysql文档中对于dual表的解释:
You are allowed to specify DUAL as a dummy table name in situations where no tables are referenced:
mysql> SELECT 1 + 1 FROM DUAL;
-> 2
DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.
mysql实现:
INSERT INTO `table` (value1, value2)
SELECT 'stuff for value1', 'stuff for value2' FROM `table`
WHERE NOT EXISTS (SELECT * FROM `table`
WHERE value1='stuff for value1' AND value2='stuff for value2';
列子:
INSERT INTO `table` (value1, value2)
SELECT 'a', 123 FROM dual
WHERE NOT EXISTS (SELECT * FROM `table`
WHERE value1='a' AND value2='123';
如果数据库已添加唯一索引:也可以使用ignore, Replace, ON DUPLICATE KEY UPDATE,存在则更新,不存在则插入