今天開發的操作在一個多對多表中需要插入關聯記錄,實際上一條和多條在我的實現功能上沒有差異,可就是多條重復記錄看起來別扭,畢竟還是不好,於是琢磨這事情。
之前最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.
作者“onedada”