我必须使用非常复杂的查询来解决问题。让我们为您总结一下:
The function should receive a customer number as an input parameter. If this
number is not contained in the tablecustomer, - 1 is to be output.
Otherwise, the customer bonus points are to be calculated. These result from
the reservations made by the customer.
The bonus points per reservation are calculated by multiplying the number of
reserved seats by the flight duration of the flight.
我已经尽力了并且解决了这个问题:
CREATE FUNCTION customer_bonus(inputnumber INT(11))
RETURNS int
DETERMINISTIC
RETURN
CASE
WHEN
(SELECT COUNT(customer.ID) FROM customer WHERE inputnumber =
customer.ID) >= 1
THEN
(SELECT customer.ID, SUM(SELECT
flightexecution.FlightDurationInMinutes *
reservation.NoReservedSeats from customer, flightexecution,
reservation where inputnumber = customer.ID))
from customer, flightexecution, reservation
WHERE reservation.CustomerID = customer.ID AND customer.ID = inputnumber
AND flightexecution.FlightNo = reservation.FlightNo
AND reservation.DepartureDate = flightexecution.DepartureDate)
ELSE -1
END;
我运行以下查询进行测试: 从客户c中选择c.id,customer_bonus(c.ID);
结果只是一个“ OK”,表示有问题。
有趣的是:当我尝试简单的Select语句时,它就起作用了。
你们中有人可以帮助我吗?
答案 0 :(得分:1)
您使用的查询可能会返回多个2字段结果。尝试返回源自查询的int时,该查询只能有一个结果,且单个字段可转换为int。我认为这是您可能正在寻找的查询:
SELECT SUM(fe.FlightDurationInMinutes * r.NoReservedSeats) AS bonusPoints
FROM reservation AS r
INNER JOIN flightexecution AS fe
ON r.FlightNo = fe.FlightNo
AND r.DepartureDate = fe.DepartureDate
WHERE r.CustomerID = inputnumber
当使用显式JOIN时,您会发现查询变得更加清晰。老实说,我不知道为什么有人会把隐式联接作为一种好奇心而已。近二十年来,人们一直认为它们(最好)是不良形式。
使用显式联接,很显然您的SUM(SELECT
子查询根本没有联接条件;表示您最终计算出的总和将是flightexecution
和reservation
每种组合的[飞行时间] * [保留席位],无论它们与customer
或每种关系如何其他。