1、按name,email建立唯一索引; 2、用SQL语句 也可以将要插入的记录存入表中。 insert into tt select distinct '1' as id,'kk','[email protected]' from temp a left join tt b on a.id=b.id and a.name=b.name and a.email=b.email where isnull(b.id)
or 将'1','kk','[email protected]'),('2,'ll','[email protected]'),('3','kk','[email protected]') 存入TMP中 insert into tt select * from tmp a left join tt b on a.id=b.id and a.name=b.name and a.email=b.email where isnull(b.id)
OR 去掉ID限制 insert into tt select * from tmp a left join tt b on a.name=b.name and a.email=b.email where isnull(b.id)
由于数据量有可能会比较大,如果在每插一条记录之前用程序进行判断,那么有N条记录就需要再次查询多少次DB是否有重复
可能效率不高?
至于IGNORE 试着写了一下 没有成功 希望能给个例子最好 谢谢
Query OK, 0 rows affected (0.06 sec)mysql> insert into ignore_t values (1),(2),(3),(4),(5);
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0mysql> select * from ignore_t;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+----+
5 rows in set (0.00 sec)mysql> insert into ignore_t values (1),(2),(3),(4),(5),(6),(7);
ERROR 1062 (23000): Duplicate entry '1' for key 1
mysql> select * from ignore_t;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+----+
5 rows in set (0.00 sec)mysql> insert ignore into ignore_t values (1),(2),(3),(4),(5),(6),(7);
Query OK, 2 rows affected (0.03 sec)
Records: 7 Duplicates: 5 Warnings: 0mysql> select * from ignore_t;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
+----+
7 rows in set (0.00 sec)
注意ID3记录的NAME与ID1相同,EMAIL与ID2相同,这种情况是允许的。
现在要插入记录 ('1','kk','[email protected]')----不允许,而判断标准并不是由于ID=1来决定的,而是由于后面的NAME与EMAIL与已存在记录有重复。
如果现在要插入('4','kk','[email protected]')----不允许,理由同上,但是用IGNORE也可以插入,因为ID不同了。
如果现在要插入('1,'kk','[email protected]')----允许,因为虽然NAME=KK存在,但是同样NAME=KK,但同时[email protected]的记录并不存在,哪怕ID是存在的,在这种情况下用IGNORE是插不进去的,因为ID有重复。所以综合考虑,INGORE应该解决不了这种情况。还请大家多多支持,3Q
2、用SQL语句
也可以将要插入的记录存入表中。
insert into tt
select distinct '1' as id,'kk','[email protected]' from temp a
left join tt b
on a.id=b.id and a.name=b.name and a.email=b.email
where isnull(b.id)
将'1','kk','[email protected]'),('2,'ll','[email protected]'),('3','kk','[email protected]')
存入TMP中
insert into tt
select * from tmp a
left join tt b
on a.id=b.id and a.name=b.name and a.email=b.email
where isnull(b.id)
去掉ID限制
insert into tt
select * from tmp a
left join tt b
on a.name=b.name and a.email=b.email
where isnull(b.id)
方法1.建唯一索引不可行啊,因为允许单独NAME或EMAIL相同,条件却是不全相同。也就是满足 name!=$name && email!=$email 而不是 name!=$name || email!=$email.方法2.临时表的方法我也想过,可是记录量可能很大,百万级,而且需要比较的字段名也是15个左右,LEFT JOIN以后效率好像不是很高。还是希望找到更好的办法,如果实在不行就只能用临时表来解决了。