简体   繁体   中英

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

$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

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)

Issue 2

AND if random product_id status = 0 , try another random product_id with status = 1 ... without breaking loop

I tried INSERT SELECT, INSERT SELECT WHERE EXISTS, ...

Don't use a separate query to get min/max product IDs. Use a JOIN with the product table in an INSERT... SELECT .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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