避免重复进入MySQL数据库的最佳方法我有一个3列的表-id(PK),pageId(FK),name。我有一个php脚本,它将大约5000条记录转储到表中,其中大约一半是重复的,具有相同的pageId和名称。页面ID和名称的组合应该是唯一的。当我在php中循环脚本时,防止复制被保存到表中的最佳方法是什么?
3 回答
慕森王
TA贡献1777条经验 获得超3个赞
ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name);
无视它? INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo");
覆盖以前输入的记录? INSERT INTO thetable (pageid, name, somefield)VALUES (1, "foo", "first")ON DUPLICATE KEY UPDATE (somefield = 'first') INSERT INTO thetable (pageid, name, somefield)VALUES (1, "foo", "second")ON DUPLICATE KEY UPDATE (somefield = 'second')
更新一些柜台? INSERT INTO thetable (pageid, name)VALUES (1, "foo"), (1, "foo")ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1)
开满天机
TA贡献1786条经验 获得超13个赞
alter table YOURTABLE add unique index(pageId, name);
$already_done = array();foreach ($records as $record){ $unique_hash = md5($record['name'].$record['pageId']); if (!in_array($unique_hash, $already_done)) { $already_done[] = $unique_hash; // sql insert here }}
- 3 回答
- 0 关注
- 425 浏览
添加回答
举报
0/150
提交
取消