How to filter SQL results in a has-many-through relation

后端 未结 13 1430
有刺的猬
有刺的猬 2020-11-21 05:17

Assuming I have the tables student, club, and student_club:

student {
    id
    name
}
club {
    id
    name
}
stude         


        
13条回答
  •  余生分开走
    2020-11-21 05:57

    WITH RECURSIVE two AS
        ( SELECT 1::integer AS level
        , student_id
        FROM tmp.student_club sc0
        WHERE sc0.club_id = 30
        UNION
        SELECT 1+two.level AS level
        , sc1.student_id
        FROM tmp.student_club sc1
        JOIN two ON (two.student_id = sc1.student_id)
        WHERE sc1.club_id = 50
        AND two.level=1
        )
    SELECT st.* FROM tmp.student st
    JOIN two ON (two.student_id=st.id)
    WHERE two.level> 1
    
        ;
    

    This seems to perform reasonably well, since the CTE-scan avoids the need for two separate subqueries.

    There is always a reason to misuse recursive queries!

    (BTW: mysql does not seem to have recursive queries)

提交回复
热议问题