Advertisement
kamiram

referer recursive 2

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