简体   繁体   中英

SQL INSERT if username doesn't exist

what is wrong with this query:

INSERT INTO `customers`(`username`, `password`) 
            VALUES (:username, :password)
            WHERE NOT EXISTS (
                SELECT `username` FROM `customers` WHERE `username`=:username
            );

What's wrong with the query? It generates a syntax error.

If you want to prevent duplicates, then use a unique constraint on the table:

ALTER TABLE customers ADD CONSTRAINT unq_customers_username UNIQUE (username);

Then if you attempt to insert a duplicate value using

INSERT INTO `customers`(`username`, `password`) 
     VALUES (:username, :password);

You will get an error of a constraint violation.

Often in this case, you want to actually update the password in the existing row. You can do that using the MySQL extension ON DUPLICATE KEY UPDATE :

INSERT INTO `customers`(`username`, `password`) 
     VALUES (:username, :password)
     ON DUPLICATE KEY UPDATE password = :password;

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