Advertisement
kamiram

referer recursive 4

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