[英]How to insert a row's primary key in to another one of its columns?
I find myself doing this a lot: 我发现自己经常这样做:
mysql_query("INSERT INTO employees (name, age) VALUES ('$name', '$age')");
$id = mysql_insert_id();
mysql_query("UPDATE employees SET pID = $id WHERE id = '$id'");
This is just an example but I often need to include the newly inserted row's ID in to another one of its columns and I am forced to use this cumbersome solution. 这只是一个示例,但是我经常需要将新插入的行的ID包含在其另一列中,因此我不得不使用这种麻烦的解决方案。 Is there any other way? 还有其他办法吗?
Since you don't know what the insert id is beforehand, there is no other way to do this (short of getting the max ID and using it in the insert query, but that's still another query). 由于您事先不知道插入ID是什么,因此没有其他方法可以做到这一点(除了获得最大ID并在插入查询中使用它,但这仍然是另一个查询)。 Why do you need to do it "a lot," though? 但是,为什么需要“很多”呢? Create a function that will do just that for you. 创建一个可以为您完成此任务的函数。
The better question is: why do you need the ID to be in two columns in the same table? 更好的问题是:为什么您需要将ID放在同一表的两列中?
You can do it in a single call from php to mysql if you use a stored procedure: 如果使用存储过程,则可以在一次从php到mysql的调用中完成:
Example calls 调用示例
call insert_employee('f00',32);
call insert_employee('bar',64);
$sql = sprintf("call insert_employee('%s',%d)", $name, $age);
Script 脚本
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 ;
@John Smith - there are differing models of heirarchial data - yourchosen one can be difficult to work with... @约翰·史密斯-层次结构数据有不同的模型-您选择的一个可能很难使用...
have a look at some other methods 看看其他方法
http://php.net/manual/en/function.mysql-insert-id.php http://php.net/manual/zh/function.mysql-insert-id.php
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.