我已经为航班客户数据库编写了一个sql函数,该函数可以为客户计算奖励。假设有一个餐桌顾客和一个餐桌预订。如果客户在某个航班上保留了一些座位,则将获得有关飞行持续时间的奖励。如果客户ID未出现在预订表中,它将返回赠金,否则将计算赠金。
CREATE FUNCTION `test5`(ID int(11) ) RETURNS int(11)
BEGIN DECLARE result int;
if (select ID from customer where ID not in (select CustomerID from reservation) limit 1) then set result = -1;
else if (select ID from customer where ID in (select CustomerID from reservation) limit 1) then set result = (select sum(c.NoReservedSeats*f.FlightDurationInMinutes) as Bonus
from reservation c, flightexecution f where c.FlightNo=f.FlightNo
and f.DepartureDateAndTimeUTC = c.DepartureDateAndTimeUTC
and c.CustomerID = c.CustomerID group by c.CustomerID limit 1) ;
end if;
end if;
RETURN result;
END
这些是预订表中CustomerID的奖励值
+-------+
| Bonus |
+-------+
| 360 |
| 180 |
| 2280 |
| 2040 |
| 180 |
| 7180 |
+-------+
因此第一个if语句有效,但是第二个if语句无效,我必须设置限制1,因为否则会得到“错误1242子查询返回多个行”。但是用这个限制1表达式,我为每个客户获得360奖金,这是我的问题。
答案 0 :(得分:0)
您不测试ID参数是否在reservations
中。应该是:
IF EXISTS (SELECT * FROM reservations WHERE CustomerID = ID)
THEN SET result = (SELECT ...)
ELSE SET result = -1
END IF;
RETURN result;
此外,您应该避免对过程参数使用与查询的任何表中的列相同的名称。名称是引用查询中的参数列还是表列可能会造成混淆。