之前最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文档中对于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.
上一篇:Android中如何使用本地广播