mysql插入不重复记录

来源:互联网 发布:2016网络诈骗案破案率 编辑:程序博客网 时间:2024/04/28 02:14
方法1:
一句sql解决

INSERT INTO gcm_users(name, gcm_regid, created_at)

SELECT 

'$name', '$gcm_regid', NOW() 

FROM dual 

WHERE NOT EXISTS(SELECT * FROM gcm_users WHERE name='$name' )

其中,gcm_users是需要进行数据插入的表,'$name', '$gcm_regid', NOW() 是需要插入的一条记录。

MySQL中的dual表解释如下:
Table - `dual`:a dummy table in mysql 
mysql文档中对于dual表的解释:
You are allowed to specify DUAL as a dummy table name in situations where no tables are referenced: 
mysql> SELECT 1 + 1 FROM DUAL;
        -> 2
DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced. 



方法2:使用INSERT INTO… ON DUPLICATE KEY UPDATE

链接:

http://blog.zol.com.cn/2299/article_2298921.html

http://blog.lyphp.com/archives/527






方法3:使用符合主键,多个判断条件字段组合成一个复合主键
链接:

方法4:建唯一索引  用ignore into插入数据


方法5:使用存储过程,不知道mysql是否适用?

http://bbs.csdn.net/topics/390316341





当数据达到上百万条的时候,以上几种方法,哪个方法的性能最佳?

在相关的例上创建一个唯一索引 create unique index ..


0 0
原创粉丝点击