Advertisement
kamiram

referer recursive 3

Dec 10th, 2023 (edited)
1,438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PL/SQL 1.39 KB | Source Code | 0 0
  1. DROP FUNCTION IF EXISTS get_referers(param_user_id bigint, param_user_bm_id SMALLINT) cascade;
  2. CREATE FUNCTION get_referers(param_user_id bigint, param_user_bm_id SMALLINT)
  3. returns TABLE  (
  4.         referer_id bigint,
  5.         referer_level INTEGER
  6. )  
  7. AS $end$
  8.     DECLARE
  9.         origin_referer_id bigint;
  10.         origin_level INTEGER;
  11.     BEGIN
  12.         SELECT users.referer_id, COUNT(*) % 5 + 1
  13.         FROM users, user_bms
  14.         WHERE
  15.             users.user_id=param_user_bm_id
  16.         AND
  17.             user_bms.user_id=users.referer_id
  18.         AND
  19.             user_bms.bm_id=param_user_bm_id
  20.         GROUP BY users.referer_id
  21.         INTO origin_referer_id, origin_level;
  22.        
  23.         RETURN query WITH recursive tree AS (
  24.             SELECT origin_referer_id AS referer_id, origin_level AS referer_level  
  25.            
  26.             UNION
  27.            
  28.             SELECT
  29.                 users.referer_id AS referer_id,
  30.                 tree.referer_level::INTEGER - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END AS referer_level
  31.             FROM users
  32.             left join user_bms  
  33.                 ON user_bms.user_id = users.user_id AND user_bms.bm_id = param_user_bm_id
  34.             join tree
  35.                 ON tree.referer_id = users.user_id  AND users.user_id != users.referer_id
  36.             WHERE
  37.                 tree.referer_level - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END >= 0
  38.             )
  39.             SELECT tree.referer_id, origin_level FROM tree ORDER BY tree.referer_level limit 1;
  40.     END;
  41. $end$
  42. language plpgsql;
  43.  
  44.  
  45. SELECT * FROM get_referers(1122::bigint, 1::SMALLINT);
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement