假如我php需要将1000条数据插入到MySQL某个字段,但是我前提需要知道数据库这个字段内有没有和我这1000条数据重复的,有重复就不写入库,没有重复的有多少就写入多少。
如果一条条去查询去写入很费资源。SQL应该怎么写才好呢?
看你的数据是否可以覆盖,可以的话使用replace into 不可以的话 就设置唯一键
用了INSERT IGNORE INTO忽略重复搞定了
你可以用,insert into ...... where id not in(select id from tb)
可以将数据库的字段设置成唯一索引
create temporary table if not exists tmp_table(id int auto_increment primary key,thisfield int);
insert into tmp_table(thisfield) values(1),(2),(3);#用Php把1000条数据拼起来插入临时表
#table1指要插入的表,thisfield指这个字段
insert into table1(thisfield)
select thisfield
from tmp_table as a
left join table1 as b on a.thisfield=b.thisfield
where b.id is null
group by a.thisfield
可以在 php 上进行判断呀