简体   繁体   English

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

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

I have two tables: p_model: (id auto inc), (name), (p_category_id) AND p_category: (id), (name) 我有两个表:p_model:(id auto inc),(名称),(p_category_id) p_category:(id),(名称)

Basically every model is associated by a category. 基本上,每个模型都由一个类别关联。 I need to generate a INSERT statement that inserts a new model and adds the id of the p_category associated to it. 我需要生成一个INSERT语句,该语句将插入一个新模型并添加与之关联的p_category的ID。

My PHP Function Passes both values: 我的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.

....
}

An example call to the function would be $database->Perform_Insert_Model("Banana","Fruit"). 该函数的示例调用为$ database-> Perform_Insert_Model(“ Banana”,“ Fruit”)。 Banana would then be a new product model and have a foreign key association of fruit's ID. 香蕉将成为一种新产品,并具有水果ID的外键关联。

You can try this kind of query (this is just 1 query): 您可以尝试这种查询(这只是1个查询):

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

Note: this assumes there is only 1 category by the given category_name or it will insert multiple records in p_model 注意:这假定给定category_name只有1个类别,否则它将在p_model中插入多个记录

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

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