如何防止在mysql插入查询中重复记录?

时间:2010-12-06 08:25:23

标签: mysql duplicate-data duplicates insert-query

我一直在将数据插入到mysql表中我在插入之前使用select对该数据以避免重复记录,如果查询返回null,则我插入记录。

但我认为这可能不是一种专业的方式来完成这项工作。

你能告诉我你的做法吗?

4 个答案:

答案 0 :(得分:1)

如果您不希望使用主键或唯一索引的原因是由于此错误将生成(如果您在单个查询中插入多行,则会出现问题),您可以使用以下语法

insert ignore into [tablename] () VALUES ()

您也可以使用ON DUPLICATE KEY UPDATE来更新某些字段。

insert into [tablename] () VALUES () ON DUPLICATE KEY UPDATE

有关详细信息,请查看http://dev.mysql.com/doc/refman/5.1/en/insert.html

答案 1 :(得分:0)

执行此操作的“专业”方法是使用主键约束。

答案 2 :(得分:0)

$qry="INSERT username INTO users";
if(!mysql_query($qry))
{
  if(mysql_errno()=1062)
  {
    echo 'Unique costraint violation!';
  }
  else
  {
    //other error
  }
}

答案 3 :(得分:0)

You can try the following example. I would suggest you to try this first in your testing environment then you can implement this in your actual scenario.

Follow the below steps:

Step 1: create a table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Step 2: Run this query multiple times and check that only one row is inserted

INSERT INTO `student` ( `name`, `age`)
SELECT `name`, `age` FROM `student`
WHERE NOT EXISTS (SELECT 1
    FROM `student`
    WHERE `name` = 'manish'
    AND `age` = '23'
    );