I am working with a database for an animal sanctuary where people can make donations to specific animals. I am trying to create a function that would return which animal a donor has donated to the most. The table I am working on is called donations and the columns are donation_id, donor_id, animal_id, amount, and date_donated.
I have tried this query(and alterations of it) but continuously have gotten errors. I am hoping to have the function return favAnimal as the animal_id of the animal the selected donor has donated to the most.
DELIMITER //
CREATE FUNCTION FindFavAnimal(p_donor_id INT(3))
RETURNS INT(3)
BEGIN
DECLARE favAnimal INT(3)
SELECT SUM(amount) AS sum_amount
FROM donations
WHERE donor_id = p_donor_id
GROUP BY animal_id;
SET favAnimal = MAX(sum_amount);
RETURN favAnimal;
END //
DELIMITER ;
Any help is greatly appreciated!
2
Answers
you were almost there. since you said only need the animal_id of the animal a selected donor has donated to the most, you do not need to return the
SUM(amount)
in your outer query. try thisNeither BEGIN-END nor DELIMITER needed.
PS. Your function name seems to be not correct – you return maximal donation sum, not according animal ID/name.