开发的操作在一个多对多表中需要插入关联记录,实际上一条和多条在我的实现功能上没有差异,可就是多条重复记录看起来别扭,毕竟还是不好,于是琢磨这事情。
之前最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.