MySQL: INSERT and auto increment based on condition

658 Views Asked by At

I am using InnoDB. My table structure is as follows:

CREATE TABLE `generic_part_name` (
 `ID` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
 `ID_Lang` tinyint(3) unsigned NOT NULL,
 `Name` varchar(250) NOT NULL,
 PRIMARY KEY (`ID`,`ID_Lang`),
 UNIQUE KEY `Name_Lang_UNIQUE` (`Name`,`ID_Lang`),
) ENGINE=InnoDB AUTO_INCREMENT=4600 DEFAULT CHARSET=utf8;

As you may see I use a composite primary key and one part of the key is an auto increment column. Now if a condition exists on another table I want to prevent the autoincrement and use an existing ID for the key pair ID-ID_Lang. For example if I have the records ID:1 ID_Lang:1 Name:Cat ID:2 ID_Lang:1 Name:Dog and I want to add a translation for Cat in French the new record would be ID:1 ID_Lang:2 Name:Chat
Now I need to insert multiple records, and some will be getting an automatic ID, others will use an existing one depending if a value exists on the other table. Is it possible to do it in a single INSERT ... SELECT statement or do I have to use a cursor?

0

There are 0 best solutions below