简体   繁体   English

在UNION语句的子查询B中引用子查询A的结果?

[英]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. 您可能希望在外部查询中select distinct ,或者在内部查询中select distinct union ”。

The query itself might be more complicated if your relationships have cycles. 如果您的关系具有周期,则查询本身可能会更复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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