0

我有表定义:

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;

它很好,很好用。

但是当我添加一个新用户时,我使用下一个查询:

insert into users (username, pass) values('test', 'test');

但是如何在 users_description 表中自动添加用户 ID?与此类似的东西:

insert into users_description values(
                                    select id from users where username = 'test',
                                     'user description');

我只想使用两个查询,这可能吗?

4

3 回答 3

3

您可以使用LAST_INSERT_ID()获取最后插入的主键 id(来自users表):

INSERT INTO users_description VALUES 
(LAST_INSERT_ID(), 'test', 'user description');
于 2012-08-16T03:47:05.943 回答
0

使用LAST_INSERT_ID(). 这里的例子。

于 2012-08-16T03:48:27.280 回答
0
$query = mysql_query("insert form (username, pass) values('test', 'test')");
$id = mysql_insert_id();

为您提供 PHP 中最后插入的 id ..

于 2012-08-16T03:49:36.700 回答