[英]MySQL : insert only if another table condition … AND retry if not
Tables表
product![]() |
review![]() |
---|---|
product_id ![]() |
product_id ![]() |
status![]() |
author![]() |
text![]() |
I select the minimum and maximum product_id's我 select 最小和最大 product_id 的
$query_select = "SELECT MIN(product_id) as min_id, MAX(product_id) as max_id FROM product";
$res_select = $con->query( $query_select );
$row = $res_select->fetch_assoc();
$min_id = $row["min_id"];
$max_id = $row["max_id"];
And I enter values in another table with random product_id我用随机 product_id 在另一个表中输入值
array loop
$query_insert = "INSERT INTO review ( product_id, author, text) VALUES (" . rand( $min_id, $max_id ) . ",'" . $data[ "name" ] . "','" . $data[ "commentary" ] . "')";
Issue 1第一期
BUT only insert if random product_id
status = 1
(I cannot use WHERE status = 1
in query_select with MIN and MAX)但仅在随机
product_id
status = 1
时插入(我不能在 query_select 中使用WHERE status = 1
和 MIN 和 MAX)
Issue 2第 2 期
AND if random product_id status = 0
, try another random product_id
with status = 1
... without breaking loop并且如果随机 product_id
status = 0
,请尝试另一个status = 1
的随机product_id
... 不中断循环
I tried INSERT SELECT, INSERT SELECT WHERE EXISTS, ...我试过 INSERT SELECT, INSERT SELECT WHERE EXISTS, ...
Don't use a separate query to get min/max product IDs.不要使用单独的查询来获取最小/最大产品 ID。 Use a
JOIN
with the product
table in an INSERT... SELECT
.在
INSERT... SELECT
中使用JOIN
与product
表。
$stmt = $con->prepare('
INSERT INTO review (product_id, author, text)
SELECT product_id, ?, ?
FROM product
WHERE status = 1
ORDER BY RAND()
LIMIT 1');
$stmt->bind_param("ss", $data["name"], $data["commentary"]);
Then call $stmt->execute()
in the insert loop.然后在插入循环中调用
$stmt->execute()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.