mysql 防止重复输入,避免重复输入mysql数据库的最佳方法

I have a table with 3 columns - id (pk), pageId (fk), name. I have a php script which dumps about 5000 records into the table, with about half being duplicates, with same pageId and name. Combination of pageId and name should be unique. What is the best way to prevent duplicates being saved to the table as I loop through the script in php?

解决方案

First step would be to set a unique key on the table:

ALTER TABLE thetable ADD UNIQUE INDEX(pageid, name);

Then you have to decide what you want to do when there's a duplicate. Should you:

ignore it?

INSERT IGNORE INTO thetable (pageid, name) VALUES (1, "foo"), (1, "foo");

Overwrite the previously entered record?

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')

Update some counter?

INSERT INTO thetable (pageid, name)

VALUES (1, "foo"), (1, "foo")

ON DUPLICATE KEY UPDATE (pagecount = pagecount + 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值