Home >Database >Mysql Tutorial >How to Perform Conditional Inserts in MySQL to Avoid Duplicate Entries?
Conditional Insertion in MySQL
Inserting data into a table with specific conditions can be achieved using conditional INSERT statements. This becomes particularly useful when you want to prevent duplicate entries or ensure data integrity. One such scenario involves inserting a new row only if the given user does not already possess a specific item.
To accomplish conditional insertion in MySQL, consider the following steps:
INSERT INTO x_table (instance, user, item) SELECT <instance_value>, <user_value>, <item_value> FROM dual WHERE NOT EXISTS (SELECT * FROM x_table WHERE user = <user_value> AND item = <item_value>)
INSERT INTO x_table (instance, user, item) SELECT 919191, 123, 456 FROM dual WHERE NOT EXISTS (SELECT * FROM x_table WHERE user = 123 AND item = 456)
This statement will only insert a new row if the combination of user=123 and item=456 does not already exist in x_table. If such a row exists, the insertion will be skipped.
The above is the detailed content of How to Perform Conditional Inserts in MySQL to Avoid Duplicate Entries?. For more information, please follow other related articles on the PHP Chinese website!