I have a table with ID
primary key (autoincrement) and a unique column Name
. Is there an efficient way in MariaDB to insert a row into this table if the same Name
doesn't exist, otherwise select the existing row and, in both cases, return the ID of the row with this Name
?
Here's a solution for Postgres. However, it seems MariaDB doesn't have the RETURNING id
clause.
What I have tried so far is brute-force:
INSERT IGNORE INTO services (Name) VALUES ('JohnDoe');
SELECT ID FROM services WHERE Name='JohnDoe';
UPDATE: MariaDB 10.5 has RETURNING
clause, however, the queries I have tried so far throw a syntax error:
WITH i AS (INSERT IGNORE INTO services (`Name`) VALUES ('John') RETURNING ID)
SELECT ID FROM i
UNION
SELECT ID FROM services WHERE `Name`='John'