INSERT INTO `table` (`value1`, `value2`)SELECT 'stuff for value1', 'stuff for value2' FROM DUALWHERE NOT EXISTS (SELECT * FROM `table`WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1)
说明:
最里面的查询
SELECT * FROM `table`WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1
用作WHERE NOT EXISTS条件,检测是否已经存在要插入数据的行。找到一行后,查询可能会停止,因此LIMIT 1(微优化,可以省略)。
中间查询
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL
表示要插入的值。DUAL指的是一个特殊的一行一列表,默认存在于所有Oracle数据库中(参见https://en.wikipedia.org/wiki/DUAL_table)。在MySQL-Server版本5.7.26中,当省略FROM DUAL时,我得到了一个有效的查询,但旧版本(如5.5.60)似乎需要FROM信息。通过使用WHERE NOT EXISTS,如果最里面的查询找到匹配的数据,中间查询返回一个空结果集。
IF (SELECT COUNT(*) FROM beta WHERE name = 'John' > 0)UPDATE alfa SET c1=(SELECT id FROM beta WHERE name = 'John')ELSEBEGININSERT INTO beta (name) VALUES ('John')INSERT INTO alfa (c1) VALUES (LAST_INSERT_ID())END
UPDATE wp_postmeta SET meta_value = ? WHERE meta_key = ? AND post_id = ?;INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT DISTINCT ?, ?, ? FROM wp_postmeta WHERE NOT EXISTS(SELECT * FROM wp_postmeta WHERE meta_key = ? AND post_id = ?);