[英]mysql - insert id from parent table
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? 但是如何在users_description表中自动添加用户ID? 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): 您可以使用
LAST_INSERT_ID()
来获取最后插入的主键ID(可以从users
表中获取):
INSERT INTO users_description VALUES
(LAST_INSERT_ID(), 'test', 'user description');
Use LAST_INSERT_ID()
. 使用
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 .. 为您提供PHP中最后插入的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.