天天看點

mysql insert 不重複資料_MySQL 插入不重複資料

今天開發的操作在一個多對多表中需要插入關聯記錄,實際上一條和多條在我的實作功能上沒有差異,可就是多條重複記錄看起來别扭,畢竟還是不好,于是琢磨這事情。

之前最naive的想法就是先對将要插入的記錄進行一次查詢,如果result set大小大于0則表明資料已經存在,不進行資料插入操作,否則insert into……,今天才明白可以一條SQL語句解決問題,利用MySQL的dual表,方法如下:

INSERT INTO users_roles

(userid, roleid)

SELECT 'userid_x', 'roleid_x'

FROM dual

WHERE NOT EXISTS (

SELECT * FROM users_roles

WHERE userid = 'userid_x'

AND roleid = 'roleid_x'

);

其中,users_roles是需要進行資料插入的表,userid_x和roleid_x是需要插入的一條記錄。

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.