Query returning exact number of rows

前端 未结 3 412
长情又很酷
长情又很酷 2021-01-27 13:14

I have a table that stores two foreign keys, implementing a n:m relationship.

One of them points to a person (subject), the other one to a specific item.

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 13:35

    I was able to come up to this simplistic solution: First returning all the values i may select then looping returning null values while we have the right amount. Posting it here if someone would stumble on the same problem. Still looking for easier/faster solutions if they exist.

    CREATE OR REPLACE FUNCTION fnk_abonemento_nariai(prm_item integer)
      RETURNS SETOF subject_items AS
    $BODY$DECLARE _kiek integer;
    DECLARE _rec subject_items;
    DECLARE _counter integer;
    BEGIN
      /*get the number of records we need*/
      SELECT INTO _kiek num_records
      FROM subjekto_abonementai
        WHERE num_id = prm_item;
    
      /*get the records that actualy exist */
    
      FOR _rec IN SELECT sub_item, sal_subject
          FROM sal_subject 
          WHERE sub_item = prm_item LOOP
        return 
          next _rec;
        _counter := COALESCE(_counter, 0) + 1;
      END LOOP;
    
      /*fill the rest with null values*/
    
      While _kiek > _counter loop
        _rec.sub_item := NULL;
        _rec.sal_subject := NULL;
        Return next _rec;
        _counter := COALESCE(_counter, 0) + 1;
      end loop;
    
    END;$BODY$
      LANGUAGE plpgsql VOLATILE;
    

提交回复
热议问题