简体   繁体   中英

Referencing Results of Subquery A in Subquery B of UNION Statement?

I'm trying to solve a problem that requires me to get rows from a table based on the values of other rows from the same table (which I also need in the output). I'm looking to do the equivalent of the below:

SELECT a.id,a.col1,a.col2 FROM tbl a WHERE col1 = @col
UNION
SELECT b.id,b.col1,b.col2 FROM tbl b WHERE b.col2 IN (SELECT a.col1)
UNION
SELECT c.id,c.col1,c.col2 FROM tbl c WHERE c.col1 IN (SELECT b.col1)

or

(SELECT id,col1,col2 FROM tbl WHERE col1 = @val) a
UNION
SELECT id,col1,col2 FROM tbl b WHERE b.col2 IN (SELECT col1 FROM a)
UNION
SELECT id,col1,col2 FROM tbl c WHERE c.col1 IN (SELECT col1 FROM b)

But both of these are not allowed. Is there some way to achieve this that avoid tediously recursive statements when extended, like the functional statement below:

SELECT * FROM #tbl WHERE col1 = @val
UNION
SELECT * FROM #tbl WHERE col2 = (SELECT col1 FROM #tbl WHERE col1 = @val)
UNION
SELECT * FROM #tbl WHERE col1 = (SELECT col1 FROM #tbl WHERE col2 = (SELECT col1 FROM #tbl WHERE col1 = @val))

fiddle

Is this what you want?

with cte as (
      SELECT a.id, a.col1, a.col2
      FROM tbl a
      WHERE col1 = @col
      UNION ALL
      SELECT b.id, b.col1, b.col2
      FROM tbl b JOIN
           cte
           ON b.col2 = cte.col1
     )
select *
from cte;

You might want select distinct in the outer query or union in the inner one.

The query itself might be more complicated if your relationships have cycles.

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