繁体   English   中英

MySQL插入到带有另一个表的外键ID的表中

[英]mySQL Insert into table with foreign key ID from another

我有两个表:p_model:(id auto inc),(名称),(p_category_id) p_category:(id),(名称)

基本上,每个模型都由一个类别关联。 我需要生成一个INSERT语句,该语句将插入一个新模型并添加与之关联的p_category的ID。

我的PHP函数传递两个值:

function Perform_Insert_Model($model_name, $category_name)
{
$statement = "INSERT INTO p_model(`name`,`p_category_id`) VALUES ('$model_name','??????')";

//Where the "??????" is I need a statement that searches for $category_name (string) in the p_category table and returns the id.

....
}

该函数的示例调用为$ database-> Perform_Insert_Model(“ Banana”,“ Fruit”)。 香蕉将成为一种新产品,并具有水果ID的外键关联。

您可以尝试这种查询(这只是1个查询):

INSERT INTO p_model(`name`,`p_category_id`) SELECT '$model_name', `p_category_id`
   FROM p_category WHERE `category_name`='$category_name';

注意:这假定给定category_name只有1个类别,否则它将在p_model中插入多个记录

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM