So I have a table like this:
create table `test` (
`testId` int(11) not null auto_increment,
`text` varchar(10) not null default '',
primary key(`testId`),
unique(`text`)
) engine=innodb;
My insert would be
- insert into
test(text) values (‘a’); - insert into
test(text) values (‘b’); - insert into
test(text) values (‘a’);
the 3rd insert will fail, but I want it to return the testId for the duplicate (for ‘a’).
Is this possible without writing a second query?
You can’t do this in an INSERT query because the INSERT does not return any rows.
When an INSERT fails because of a duplicated key – normally the thing that built the query knows what data it sent, so it could use this.
You may be able to achieve what you want by using 12.2.5.3. INSERT … ON DUPLICATE KEY UPDATE