Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

php - MySQL : insert only if another table condition ... AND retry if not

Tables

product review
product_id product_id
status author
text
question from:https://stackoverflow.com/questions/65879484/mysql-insert-only-if-another-table-condition-and-retry-if-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...