我还不太清楚该怎么做。所以我做的是一个网络游戏。当用户购买新车时,我会插入:
$c->query("INSERT INTO user_cars (carid, userid, acc, speed) VALUES ('$buyid','$id','$acc','$speed')");
现在我有另一个表,我需要在上面的查询之后从上面的查询插入信息。我需要的是carid
。用户可以拥有2辆以上的汽车。我现在该怎么办?
您有多个选项:
- 当行插入cars表时,您可以构建一个触发器来在表2中插入新行(点击此处阅读更多http://dev.mysql.com/doc/refman/5.5/en/trigger-syntax.html)
- 有一个函数mysql_insert_id(),它返回最后插入的id(点击此处阅读更多http://php.net/manual/en/function.mysql-insert-id.php)
- 如果你使用PDO,有一个smillar命令
- 等等
这是您想要创建的触发器的基本演示。为了便于说明,我还将ddl和一个示例insert包含在您的user_cars表中,以显示另一个表,我称之为"your_other_table",它接收到进入user_cars表的insert的insert(只是carid值)。
小提琴:http://sqlfiddle.com/#!9/f76a7/1/0
(注意"your_other_tabe"有一行插入到"user_cars"中,尽管它本身没有直接插入)
delimiter //
create table user_cars
(
carid int,
userid int,
acc int,
speed int,
constraint id_pk primary key (carid, userid)
)//
create table your_other_table
(
carid int
)//
create trigger your_trigger_name before insert on user_cars
for each row begin
insert into your_other_table (carid)
values (new.carid);
end
//
insert into user_cars values
(1, 2, 3, 99)//
delimiter ;
select *
from your_other_table;
输出:
| CARID |
|-------|
| 1 |
这是上面sql中唯一创建触发器的部分:
delimiter //
create trigger your_trigger_name before insert on user_cars
for each row begin
insert into your_other_table (carid)
values (new.carid);
end
//
delimiter ;