sqlsql-server-2008queueinner-joinlinked-tables

(?) SQL - interlinked joins (how to build a chain between two tables?)


First of all, that's not my table. I got a project with tables like that...

two tables with multiple switches

I need an idea to get all linked pages/questions in a queue/list in a given order.

Perfect soloution would be:

enter image description here

Do you know a way, to get this in one statement (via inner joins)? My problems are the order and also the mix between both tables, merged in one. It's also ok, if there are 2 id fields (one for each type), so than we also can go without type (for the current element).


Solution

  • You can use a couple of CTEs to first UNION the tables together and then follow through the list starting from the firstPage, using a row number to guarantee the ordering of results:

    WITH allpq AS (
      SELECT name, 'page' AS type, next, next_type
      FROM page
      UNION ALL 
      SELECT name, 'question', next, next_type
      FROM question
    ),
    list AS (
      SELECT type, name, next, next_type, 1 as rn
      FROM allpq
      WHERE name = 'firstPage'
      UNION ALL
      SELECT a.type, a.name, a.next, a.next_type, list.rn + 1
      FROM allpq a
      JOIN list ON a.name = list.next AND a.type = list.next_type
    )
    SELECT type, name, next, next_type
    FROM list
    ORDER BY rn
    

    Output:

    type        name            next            next_type
    page        firstPage       secondPage      page
    page        secondPage      firstQuestion   question
    question    firstQuestion   secondQuestion  question
    question    secondQuestion  thirdPage       page
    page        thirdPage       fourthPage      page
    page        fourthPage      fourthQuestion  question
    question    fourthQuestion  fifthPage       page
    page        fifthPage       fifthQuestion   question
    question    fifthQuestion   sixthPage       page
    page        sixthPage       seventhPage     page
    page        seventhPage     eighthPage      page
    page        eighthPage      
    

    Demo on dbfiddle