I have table definitions:
create table users(
id int not null auto_increment,
usernaname varchar(50) not null,
pass varchar(50) not null,
primary key(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table users_description(
user_id int not null,
description varchar(255),
key(user_id),
foreign key(user_id) references users(id) on delete cascade
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and it is good, works nice.
but when I add a new user I use a next query:
insert into users (username, pass) values('test', 'test');
but how to add a id of user automatically in users_description table? Something similar to to this:
insert into users_description values(
select id from users where username = 'test',
'user description');
I want to use only two queries, is this possible?
You can use LAST_INSERT_ID()
to get the last inserted primary key id (which would be from the users
table):
INSERT INTO users_description VALUES
(LAST_INSERT_ID(), 'test', 'user description');
Use LAST_INSERT_ID()
. Example here.
$query = mysql_query("insert form (username, pass) values('test', 'test')");
$id = mysql_insert_id();
gives you the last inserted id in PHP ..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.