How to Insert Select with AUTO_INCREMENT in MySQL ~ Charle's programming how tos blog
Charle's programming how tos blog: How to Insert Select with AUTO_INCREMENT in MySQL

Monday, September 22, 2008

How to Insert Select with AUTO_INCREMENT in MySQL

You want to include values and/or auto_increment selected from another table in your insert statement.
Here's how to:
Say you have created two tables as below:
create table t_lang(
lang_id integer unsigned auto_increment primary key,
lang varchar(50) not null);

create table t_geek(
geek_id integer unsigned auto_increment primary key,
geek_name varchar(50) not null,
lang_id integer unsigned not null);


To add a geek and their language specialty you'd do this:
insert into t_lang values(null,"Java");
insert into t_geek select null, "Charles", last_insert_id() from t_lang;

As simple as that!

No comments: