简体   繁体   中英

Insert only if row doesn't exist

I am using PreparedStatement to prepare sql queries. I want to insert a row in table if and only if it doesn't exist.

I tried this -

INSERT INTO users (userId) VALUES (?) ON DUPLICATE KEY UPDATE userId = ?

But this will unnecessarily update the userId.

How can i insert the userId here ?

INSERT  INTO users 
        (userId) 
SELECT  ?
WHERE   NOT EXISTS
        (
        SELECT  * 
        FROM    users 
        where   userId = ?
        )

You may use

 INSERT IGNORE INTO users (userId) VALUES (?) 

But you should understand why do you want ignore errors.

on duplicate key does not work correctly when the table is an innodb. It creates exactly the problem you are describing. If you need the functionality of an innodb, then should you first check the existence of the row, otherwise can you convert the table to a myisam table.

edit: if you need to check the existence of the row before the decision to insert or update, then would I advice you to use a stored procedure.

DELIMITER //
CREATE PROCEDURE adjustusers(IN pId int)
BEGIN
DECLARE userid int;
  select  count(id) into userid from users where id = pId;
  if userid = 1 then
   update users set id = pId where id = pId;
  else
   insert into users(id) values(pId);
  end if;
END //
DELIMITER ; 

A stored procedure is precompiled, just as a prepared statement. Hence no SQL injection problems and some more functionality and only one call to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM