我有两个表(MySQL):
productSize: {
id,
article,
size,
weight
}
productPrice: {
id,
sizeID,
price
}
大小 ID - 主要 ID 表单产品大小表。我需要在产品尺寸表中插入一个,然后在产品价格中插入或更新。
我尝试这样的事情:
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查询合并为一个查询。可能吗?如果产品价格SQL查询的连接失败,则所有过程必须重新开始,并且在产品尺寸表中将有很多不正确的项目。
我希望使用:
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);
}
INSERT
一次只能插入到一个表中,因此无法组合productSize
和productPrice
插入。但是您可以一次完成所有productPrice
插入。
foreach ($arrProductSize as $objSize) {
// insert into productSize here
$psid = mysqli_insert_id($conn);
$pp_array = array();
foreach ($arrProductPrice as $objPrice) {
$pp_array[] = "({$objPrice->id}, $psid, {$objPrice->price})";
}
$pp_query = "INSERT INTO productPrice (id, sizeID, price) VALUES " . implode(', ', $pp_array) . " ON DUPLICATE KEY UPDATE sizeID = VALUES(sizeID), price = VALUES(price)";
mysqli_query($conn, $pp_query);
}