如何使用where子句进行UPSERT

时间:2015-01-15 13:12:22

标签: mysql sql sql-update insert-update

我通过互联网浏览找到并回答这个但我无法找到答案。

我想在更新或插入之前检查四列。我不能使用INSERT ... ON DUPLICATE KEY UPDATE因为它不允许where子句。所以我试着使用我创建的以下语句。

"SELECT COUNT(id) INTO @count FROM room_prices WHERE (hotel_di = $hotel_id AND room_id = $room_id AND period_id = $periodId AND meal_plan_id = $mealPlanId) "
                . "IF @count > 0 THEN "
                . "UPDATE room_prices SET price = $price WHERE (hotel_di = $hotel_id AND room_id = $room_id AND period_id = $periodId AND meal_plan_id = $mealPlanId) "
                . "ELSE "
                . "INSERT INTO room_prices (hotel_id, room_id, period_id, meal_plan_id, price) VALUES ($hotel_id, $room_id, $periodId, $mealPlanId, $price) "
                . "END IF"

但是这个也行不通。它给出了这个错误。

您提交的查询无效。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

hotel_idroom_idperiod_idmeal_plan_id上的唯一索引开始:

CREATE UNIQUE INDEX idx_room_prices_4 on room_prices(hotel_id, room_id, period_id, meal_plan_id)

然后您可以使用on duplicate key update

INSERT INTO room_prices(hotel_id, room_id, period_id, meal_plan_id, price) 
    SELECT $hotel_id, $room_id, $periodId, $mealPlanId, $price
    ON DUPLICATE KEY UPDATE price = $price;