Advertisement
kamiram

referer recursive 3.x

Dec 10th, 2023
1,405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PL/SQL 1.38 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
  13.         FROM users
  14.         WHERE users.user_id = param_user_id
  15.         INTO origin_referer_id;
  16.  
  17.         SELECT COUNT(*) % 5 + 1
  18.         FROM user_bms
  19.         WHERE
  20.             user_bms.user_id=origin_referer_id
  21.         AND
  22.             user_bms.bm_id=param_user_bm_id
  23.         INTO origin_level;
  24.        
  25.         RETURN query WITH recursive tree AS (
  26.             SELECT origin_referer_id AS referer_id, origin_level AS referer_level  
  27.            
  28.             UNION
  29.            
  30.             SELECT
  31.                 users.referer_id AS referer_id,
  32.                 tree.referer_level::INTEGER - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END AS referer_level
  33.             FROM users
  34.             left join user_bms  
  35.                 ON user_bms.user_id = users.user_id AND user_bms.bm_id = param_user_bm_id
  36.             join tree
  37.                 ON tree.referer_id = users.user_id  AND users.user_id != users.referer_id
  38.             WHERE
  39.                 tree.referer_level - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END >= 0
  40.             )
  41.             SELECT tree.referer_id, origin_level FROM tree ORDER BY tree.referer_level limit 1;
  42.     END;
  43. $end$
  44. language plpgsql;
  45.  
  46.  
  47. SELECT * FROM get_referers(1122::bigint, 1::SMALLINT);
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement