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!

An introduction

As a programmer, you need to know quite a few languages, tools, techniques, methodologies and a lot more, all of which are available in a book or website or some other media.
My motive for starting this blog is so that we can share the knowledge we'v all gathered from these different sources.

for the benefit of all,