如何将行主键插入另一个列?

时间:2011-03-13 15:45:03

标签: php mysql sql

我发现自己做了很多这样的事情:

mysql_query("INSERT INTO employees (name, age) VALUES ('$name', '$age')");
$id = mysql_insert_id();
mysql_query("UPDATE employees SET pID = $id WHERE id = '$id'");

这只是一个例子,但我经常需要将新插入的行ID包含在另一个列中,我不得不使用这个繁琐的解决方案。还有其他办法吗?

5 个答案:

答案 0 :(得分:2)

由于您事先不知道插入ID是什么,因此没有其他方法可以做到这一点(没有获取最大ID并在插入查询中使用它,但这仍然是另一个查询)。为什么你需要“做很多”呢?创建一个能为你做到这一点的功能。

更好的问题是:为什么你需要在同一个表中的两列中使用ID?

答案 1 :(得分:1)

检查MySQL的LAST_INSERT_ID()函数here。根据您的情况,可能会或可能不是您需要的。

答案 2 :(得分:1)

如果使用存储过程,可以在从php到mysql的单个调用中执行此操作:

示例调用

call insert_employee('f00',32);
call insert_employee('bar',64);

$sql = sprintf("call insert_employee('%s',%d)", $name, $age);

<强>脚本

drop table if exists employees;
create table employees
(
id int unsigned not null auto_increment primary key,
name varchar(32) not null,
age tinyint unsigned not null default 0,
pid int unsigned not null default 0
)
engine=innodb;

drop procedure if exists insert_employee;

delimiter #

create procedure insert_employee
(
in p_name varchar(32),
in p_age tinyint unsigned
)
begin

declare v_id int unsigned default 0;

  insert into employees(name, age) values (p_name, p_age);
  set v_id = last_insert_id();
  update employees set pid = v_id where id = v_id;
end#

delimiter ;

答案 3 :(得分:1)

@John Smith - 有不同的分层数据模型 - 您选择的模型可能难以使用......

查看some other methods

答案 4 :(得分:0)

http://php.net/manual/en/function.mysql-insert-id.php

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());