0

本の主題に基づいて本の価格の平均を与える関数を作成する必要があります。この関数のルールは次のとおりです。

a) 引数が null の場合、null を返す

b) 引数がトピック テーブルにあるトピック ID と一致しない場合は、-2 の値を返します。

c) 引数がトピック テーブルにあるトピック ID と一致するが、そのトピックの本がない場合は、-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;
#

次のようなエラーが表示されます。

 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

このエラーを取り除くための提案はありますか? 構文に問題がある場合があります... よろしくお願いします。

4

2 に答える 2

0

「そのような SELECT はその結果を外部コンテキストに返さなければならない」ため、select を使用してユーザー定義変数を使用する を参照してください。次のように、最初の if ステートメントの外で select を抽出しようとします。

select avg(list_price) into v_avgListPrice
        from books 
        where topic_id = p_subject
        group by book_id
        limit 1;
if p_subject is null then
    set v_avgPrice := null;
elseif v_avgListPrice is not null then
    set v_avgPrice := v_avgListPrice;
else 
    set v_avgPrice := -2;
end if;
于 2012-10-17T22:31:38.367 に答える
0

EXISTS最初に、平均を計算するクエリを@danのように外に移動する必要があります。

しかし、そのクエリには問題があります。book_id でグループ化して制限し、最初の行に制限しようとしています。まず第一に、それはトピックごとの平均価格にはなりません。トピックごとにグループ化されていないため、各本の価格が得られるだけです。次のことを試してください。

delimiter $$

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 not exists (select * from topics where topic_id = p_subject) then
    set v_avgPrice := -2;
elseif not exists (select * from books where topic_id = p_subject) then
    set v_avgPrice := -1;
else
    select avg(list_price) into v_avgListPrice
    from books
    where topic_id = p_subject
    group by topic_id;
end if;

return v_avgPrice;
end$$

delimiter ;

MySQL が関数内のセミコロンをcreate functionステートメントの終わりとして解釈しないように、区切り文字を変更することを忘れないでください。

于 2012-10-17T23:29:34.167 に答える