PHP,SQL将值插入到链接在一起的表中?

时间:2014-04-28 16:54:17

标签: php mysql

我有两张桌子,

表用户:
Columns->身份证,姓名,年龄,职位,部门,电话

桌面电话: 列id,u_id,u_phonetype(外键是user.id,带有删除级联和更新级联)。

我想使用Phone表中的u_phonetype执行此INSERT INTO sql:

INSERT INTO `user` (`id`, `name`, `age`, `position`, `department`, 
`phone`) values ("'.$name.'", "'.$age.'", "'.$position.'", "'.$department.'", "'.$phone.'") ;

如何在此SQL中插入u_phonetype的值?我会执行JOIN吗?

2 个答案:

答案 0 :(得分:1)

使用php,您只需要使用2/3查询即可完成此操作。

// insert your user
INSERT INTO users (columns) VALUES(vals);

// get the last id
SELECT id FROM users order by id desc limit 1

// this is also work if you just do
SELECT id FROM users where name='name' and age='age' "and whatever values you have";

// then insert into phone with the id retrieved from above
INSERT INTO Phone (columns) VALUES(vals); 

3步骤过程但在相同的连接下它应该没问题

答案 1 :(得分:0)

怎么样?

LAST_INSERT_ID();

INSERT INTO table1 (column1,column2) VALUES ('test', 1); 
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (column3,column4,column5) VALUES (@last_id_in_table1, 2, 3);