How to implement "insert if not exists" operation in MySQL?
P粉005105443
2023-08-29 10:59:40
<p>I first found this article through a Google search, <em>How to write an INSERT if NOT EXISTS query in standard SQL</em>, which discusses mutually exclusive tables. </p>
<p>I have a table with about 14 million records. If I want to add more data in the same format, is there a way to ensure that the record I want to insert does not exist without using a pair of queries (i.e. one query to check and one query to insert, with the result set is empty)? </p>
Does the <code>unique</code> constraint on the <p>field guarantee that <code>insert</code> will fail if it already exists? </p>
<p>Looks like <em> is just </em> a constraint, and when I issue the insert via PHP, the script rattles. </p>
solution:
illustrate:
Innermost query
Used as a
WHERE NOT EXISTS
condition to detect whether a row containing the data to be inserted already exists. The query may stop after finding a row of this class, soLIMIT 1
(micro-optimization, can be omitted).Intermediate query
represents the value to be inserted.
DUAL
refers to a special single row single table that exists by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On MySQL-Server version 5.7.26, I get valid queries whenFROM DUAL
is omitted, but older versions (like 5.5.60) seem to require theFROM
information. By usingWHERE NOT EXISTS
, if the innermost query finds matching data, the intermediate queries will return an empty result set.External query
Insert data (if intermediate query returns any data).
Use
INSERT IGNORE INTO table
.There is also
INSERT … ON DUPLICATE KEY UPDATE
syntax, which you can use in 13.2.6.2 INSERT … ON DUPLICATE KEY UPDATE statement .Post from bogdan.org.ua According to Google's web cache: