I need to create a function that will give the average of the book prices based on books’ subjects. The rules for this function are:
a) If the argument is null, return a null
b) If the argument does not match any topic id that we have in the topics table, return a value of -2
c) If the argument matches a topic id that we have in the topics table, but we do not have any books with
that topic, return a value of -1
create function AvgPriceByTopic(
p_subject varchar(20))
RETURNS decimal(8,2)
begin
declare v_avgPrice decimal(8,2);
declare v_avgListPrice decimal(8,2);
if p_subject is null then
set v_avgPrice := null;
elseif exists (
select avg(list_price) into v_avgListPrice
from books
where topic_id = p_subject
group by book_id
limit 1 ) then
set v_avgPrice := v_avgListPrice;
else
set v_avgPrice := -2;
end if;
return v_avgPrice;
end;
#
I’m getting an error that states:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'into v_avgListPrice from books' at line 11
Any suggestions to get rid of this error? Sometimes I have trouble with the syntax… Thanks ahead of time.
First you need to move the query that calculates the average outside the
EXISTSlike @dan suggested.But I see a problem on that query: it’s grouping by book_id and limiting and then tries to limit it to the first row. First of all, that would not result in the average price by topic, because it’s not grouping by topic, it would just result each book’s price. Try the following:
Remember to change the delimiter so that MySQL does not interpret the semi-colons within the function as the end of the
create functionstatement.