简体   繁体   English

MySQL:仅在另一个表条件时插入……如果不是则重试

[英]MySQL : insert only if another table condition … AND retry if not

Tables

product产品 review审查
product_id product_id 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中使用JOINproduct表。

$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.

相关问题 将数据插入一个表中,从另一个表中删除,并在MySQL中使用时间戳记条件 - Insert data in one table, remove from another, with timestamp condition in mysql 更新后的 Mysql 触发器插入到另一个有条件的表中 - Mysql trigger after update insert into another table with condition 如何根据日期条件(PHP-MySQL-Query)将一个表中的多行插入另一个表? - How to insert multiple rows from a table to another table based on date condition (PHP-MySQL-Query)? 使用 PHP/MYSQL 需要 INSERT 到具有 IN 条件的表 - With PHP/MYSQL need to INSERT to a Table With a IN Condition MySQL插入表,值形成另一个表 - MySQL insert into table, values form another table 使用子查询将mysql表插入另一个表 - Insert a mysql table into another table with sub query 查询一个 MySQL 表并将结果插入另一个表 - Query A MySQL Table & Insert Results Into Another Table mysql,其中一个条件条件所在的表与另一个条件条件不同的表联接 - mysql, 1 table with where condition joined with another table with different where condition 仅当更新另一个表上的列或向另一个表添加新记录时,才将记录插入到新的MySQL数据库表中吗? - Insert record into new MySQL Database table only when a Column on another Table is Updated or a New record is added to that other Table? MySQL从另一个表插入随机值 - MySQL insert random values from another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM