根据另一列的值提取一列的所有行(SQL查询)
Extract all rows of a column based on the value of another column (SQL query)
我有table
a | b
-----
1 | 3
3 | 2
3 | 4
2 | 5
3 | 6
2 | 7
如何写 sql query if a = 1 then result 3 2 4 5 6 7, if a = 3 then 2 4 5 6 7, if 2 then 5 7
这是我的查询
select *
from table
where a in (select b from table where a = 1) or a = 1
但结果只有 3 2 4 6 因为 3 在 col b 中有 2 所以我也想有 5 7
谢谢
我怀疑您有一个层次结构,其中 a
是父节点,b
是子节点,并且您正在寻找给定节点的所有后代。
遍历这种结构的一种常见方法是分层查询。在 SQL 服务器中:
with cte as (
select a, b from mytable where a = @your_parameter
union all
select t.a, t.b from mytable t inner join cte c on t.a = c.b
)
select * from cte
Demo on DB Fiddle - 当给定 3 作为参数时:
a | b
-: | -:
3 | 2
3 | 4
3 | 6
2 | 5
2 | 7
我有table
a | b
-----
1 | 3
3 | 2
3 | 4
2 | 5
3 | 6
2 | 7
如何写 sql query if a = 1 then result 3 2 4 5 6 7, if a = 3 then 2 4 5 6 7, if 2 then 5 7 这是我的查询
select *
from table
where a in (select b from table where a = 1) or a = 1
但结果只有 3 2 4 6 因为 3 在 col b 中有 2 所以我也想有 5 7 谢谢
我怀疑您有一个层次结构,其中 a
是父节点,b
是子节点,并且您正在寻找给定节点的所有后代。
遍历这种结构的一种常见方法是分层查询。在 SQL 服务器中:
with cte as (
select a, b from mytable where a = @your_parameter
union all
select t.a, t.b from mytable t inner join cte c on t.a = c.b
)
select * from cte
Demo on DB Fiddle - 当给定 3 作为参数时:
a | b -: | -: 3 | 2 3 | 4 3 | 6 2 | 5 2 | 7