我通过互联网浏览找到并回答这个但我无法找到答案。
我想在更新或插入之前检查四列。我不能使用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"
但是这个也行不通。它给出了这个错误。
您提交的查询无效。
有没有办法做到这一点?
答案 0 :(得分:1)
从hotel_id
,room_id
,period_id
,meal_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;