How to implement "insert if not exists" operation in MySQL?
P粉005105443
P粉005105443 2023-08-29 10:59:40
0
2
529
<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>
P粉005105443
P粉005105443

reply all(2)
P粉338969567

solution:

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1)

illustrate:

Innermost query

SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

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, so LIMIT 1 (micro-optimization, can be omitted).

Intermediate query

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

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 when FROM DUAL is omitted, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS, if the innermost query finds matching data, the intermediate queries will return an empty result set.

External query

INSERT INTO `table` (`value1`, `value2`)

Insert data (if intermediate query returns any data).

P粉521013123

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template