我有两个表(MySQL):
productSize: {
id,
article,
size,
weight
}
productPrice: {
id,
sizeID,
price
}
sizeID - 产品尺寸表的初始 ID。我需要在productSize表中进行一次插入,然后在productPrice中进行多次插入或更新。
我尝试这样的事情:
foreach($arrProductSize as $objSize) {
/*
Insert into productSize here. Get id of new row by mysqli_insert_id()
*/
foreach($arrProductPrice as $objPrice) {
/*
Insert or update into productPrice.
Save primery id from productSize new row into productPrice new row.
*/
}
}
但我希望将所有 sql 查询合并为一个查询。是否可以?如果productPrice sql查询连接失败,所有过程都必须重新开始,并且productSize表中将会有很多不正确的项目。
我想使用:
mysqli_multi_query($dbi, "INSERT INTO productSize(article,size,weight) VALUES ('','','');INSERT INTO productPrice(sizeID,price) VALUES ('4','');");
但是 sizeID(=4) 我需要获取 pfor prevois 插入查询。
最佳答案
您可以在插入语句中使用类似选择查询的内容 http://dev.mysql.com/doc/refman/5.7/en/insert-select.html
foreach($arrProductSize as $objSize){
$query = "INSERT INTO productSize(article,size,weight) VALUES ('','','');";
foreach($arrProductPrice as $objPrice) {
$query .= "INSERT INTO productPrice(sizeID,price)
SELECT id, '{$bjPrice->price}' FROM productSize order BY id desc limit 1; "
}
mysqli_query($dbi,$query);
}
关于php - 如何构建相互依赖的多sql插入查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806807/