简体   繁体   中英

Mysql INSERT IGNORE INTO ignore only one column

I have used the following sql on my website

$sql = "INSERT IGNORE INTO names VALUES ('akku@gmail.com','19','akku');";

This code only works if both three values are same. .I need to Insert the data to the database only if first value (akku@gmail.com) is not exists on the database. Else it should display "email already exists". Also it should work even if the second and third values are different.

Make the email address the primary key of your table. Don't use the IGNORE keyword in the statement. Catch the error that arises when a duplicate email is entered (attempting to insert the duplicate into MySQL will cause an exception in your front end code) and display an "email already exists" message

The database doesn't care what your values are so I don't really understand what you mean by "it only works if the last two are he same" unless you have a trigger that raises an error if you attempt to insert differing values for your last two columns

You can use SELECT first to find if the data is there, and then insert if it isn't or update if it is. This would be the best way as you can use php to handle any case using this.

Second way would be to make first value primary key. This way your insert would throw an error and you can catch that to do whatever you want.

Third way, in which if you want to update data if it exist would be using- INSERT ON DUPLICATE KEY UPDATE https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/

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