简体   繁体   中英

Recursive SQL query only returning single reference instead of recursive references

I have a DB table

id (INT, NOT NULL)  
username (NVARCHAR, NOT NULL)  
holiday_replacement (INT, NULL)

The holiday_replacement is either NULL or it references a value in the id field.

Now, it would be trivial to determine for whom a specified id was the holiday_replacement , but to complicate this query the holiday_replacement may be chained.

In simpler terms, a user may have a holiday_replacement who themselves has a holiday_replacement .

In such a case the query should return a list of all users in this ' holiday replacement graph '.

Currently I have

WITH user_graph AS (
    SELECT
        *
    FROM
        table_name
    WHERE
        holiday_replacement = @current_user_id

    UNION ALL

    SELECT
        tn.*
    FROM
        table_name tn
        JOIN user_graph ug ON ug.holiday_replacement = tn.id
) 
SELECT
    id
FROM
    user_graph 

However, this query only returns those users who have directly referenced @current_user_id as their holiday_replacement and doesn't consider any other users who should also be returned on account of this chaining.

For example, if I have the following 3 users:

id = 1, username = 'user_1', holiday_replacement = NULL  
id = 2, username = 'user_2', holiday_replacement = 1  
id = 3, username = 'user_3', holiday_replacement = 2

then for @current_user_id = 1, the query should return

id
---
 2
 3

but presently it only considers that directly referenced user and returns

id
---
 2

I just can't wrap my head around what I need to change. Can anyone help?

use below code

WITH user_graph AS (
SELECT
    *
FROM
    table_name
WHERE
    holiday_replacement = @current_user_id

UNION ALL

SELECT
    tn.*
FROM
    table_name tn
    JOIN user_graph ug ON ug.id =tn.holiday_replacement 
) 
SELECT
    id FROM
    user_graph 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM