Advertisement
kamiram

referer recursive 4.x

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