Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- DROP FUNCTION IF EXISTS get_referers(param_user_id bigint, param_user_bm_id SMALLINT) cascade;
- CREATE FUNCTION get_referers(param_user_id bigint, param_user_bm_id SMALLINT)
- returns TABLE (
- referer_id bigint,
- referer_level INTEGER
- )
- AS $end$
- BEGIN
- RETURN query WITH recursive tree AS (
- SELECT
- users.referer_id AS referer_id,
- (
- SELECT COUNT(*) % 5 + 1
- FROM user_bms
- WHERE
- user_bms.user_id=users.referer_id
- AND
- user_bms.bm_id=param_user_bm_id
- )::INTEGER AS referer_level
- FROM users
- WHERE users.user_id = param_user_id
- UNION
- SELECT
- users.referer_id AS referer_id,
- tree.referer_level::INTEGER - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END AS referer_level
- FROM users
- left join user_bms
- ON user_bms.user_id = users.user_id AND user_bms.bm_id = param_user_bm_id
- join tree
- ON tree.referer_id = users.user_id AND users.user_id != users.referer_id
- WHERE
- tree.referer_level - CASE WHEN user_bms IS NULL THEN 0 ELSE 1 END > 0
- )
- SELECT * FROM tree ORDER BY referer_level limit 1;
- END;
- $end$
- language plpgsql;
- SELECT * FROM get_referers(1122::bigint, 1::SMALLINT);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement