Home >Database >Mysql Tutorial >How to Perform Conditional Inserts in MySQL?

How to Perform Conditional Inserts in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 20:41:10464browse

How to Perform Conditional Inserts in MySQL?

Achieving Conditional Inserts in MySQL

In MySQL, conditional inserts can be challenging due to the absence of specific keywords dedicated to this purpose. Hence, alternative approaches must be employed.

Approach Using a Subquery:

One effective solution is to use a subquery to check for existing rows with matching criteria. The following query will insert a new row into the x_table only if a row with the same user and item values does not exist:

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);

The subquery ensures that the INSERT statement executes only if the condition is met. dual is a single-row table that provides a convenient source for the SELECT statement.

Alternative Approach with MERGE:

Another option for conditional inserts is to use the MERGE statement. The MERGE statement allows for both insertion and updates in a single operation. The following query will insert a new row into the x_table if it does not already exist, otherwise it will update the existing row:

MERGE INTO x_table AS target
USING (
  SELECT 919191 AS instance, 123 AS user, 456 AS item
) AS source
ON target.user = source.user AND target.item = source.item
WHEN NOT MATCHED THEN INSERT (instance, user, item) VALUES (source.instance, source.user, source.item)
WHEN MATCHED THEN UPDATE SET instance = source.instance;

In this approach, the MERGE statement first checks for an existing row with matching user and item values. If no match is found, a new row is inserted using the data from the source subquery. If a match is found, the instance value is updated.

The above is the detailed content of How to Perform Conditional Inserts in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn