0

I am new in SQL and I am trying to do a recursive query over the same table to find the brokers of the "master brokers" I have a table that looks like this (it can grow to any amount of rows and deepness)

enter image description here

So I need a result like this:

master_id => broker_id

enter image description here

I have checked about how to do it and I got:

WITH admin_has_master_brokers
AS (
    SELECT DISTINCT master_broker_id, admin_id
        FROM admin_has_master_brokers
            
    UNION ALL
    /*I DO NOT KNOW HOW TO DO THIS SECTION*/
    SELECT    
        master_broker_id, admin_id
    FROM admin_has_master_brokers
)
SELECT 
    *
FROM 
    admin_has_master_brokers
ORDER BY master_broker_id ASC

But I can not understand how to do the recursive part to only get the results I need because I am getting this:

enter image description here

Any idea?

9
  • What do you mean by: "I DO NOT KNOW HOW TO DO THIS SECTION"? What result are you getting from the query compared to your expectation? Is it not the same? Commented Jul 15, 2021 at 6:49
  • @AlexanderFalk hey mate I have added the result I am getting Commented Jul 15, 2021 at 7:18
  • Add GROUP BY master_broker_id. Commented Jul 15, 2021 at 7:19
  • @Grumpy no, the results get reduced... did not work Commented Jul 15, 2021 at 7:24
  • What MySQL version? Commented Jul 15, 2021 at 7:53

1 Answer 1

2

Povided original table is Mytable the query lists all desendants of every master_broker_id.

WITH RECURSIVE admin_has_master_brokers
AS (
    SELECT DISTINCT master_broker_id master, master_broker_id, admin_id
    FROM mytable
       
    UNION ALL

    SELECT a.master,  
        m.master_broker_id, m.admin_id
    FROM admin_has_master_brokers a
    JOIN mytable m ON m.master_broker_id = a.admin_id
)
SELECT DISTINCT master, admin_id    
FROM 
    admin_has_master_brokers
ORDER BY master, admin_id
Sign up to request clarification or add additional context in comments.

2 Comments

Nice, but the query is missing the word RECURSIVE
@FaNo_FN, thank you. Missed mariadb tag, corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.