sql - 如何在 SQL Server 中选择父行和子行

标签 sql sql-server select common-table-expression

我想从下表中选择与 user_id 53( parent 和 child )相关的所有项目。应该是:1、2、4、8、9。

my_table
--------------------------------------------
id    parent_id   user_id   sequence   depth
--------------------------------------------
1     null        50        1          1
2     1           52        1.2        2
3     1           52        1.3        2
4     2           53        1.2.4      3
5     2           52        1.2.5      3
6     3           52        1.3.6      3
7     3           51        1.3.7      3
8     4           51        1.2.4.8    4
9     4           51        1.2.4.9    4

使用 CTE,我可以选择所有 child 或 parent ,但无法仅通过一个查询来选择 child 和 parent 。下面是我用来选择子项的 cte。

项目和子项目

with cte as (
    select t.id, t.parent_id, t.user_id 
    from my_table t 
    where t.user_id=53

    union all

    select t.id, t.parent_id, t.user_id 
    from my_table t
    inner join cte c on (c.parent_id=t.id)
)
select t.* from cte t;

项目和父项

with cte as (
    select t.id, t.parent_id, t.user_id 
    from my_table t 
    where t.user_id=53

    union all

    select t.id, t.parent_id, t.user_id 
    from my_table t
    inner join cte c on (c.id=t.parent_id)
)
select t.* from cte t;

谢谢。

最佳答案

有序列非常方便。 parent 有一个序列与您正在寻找的序列的初始子集相匹配。对于 child 来说也是如此,但相反。

以下内容接近您想要的:

select mt.*
from (select sequence from my_table where USER_ID = 53) theone join
     my_table mt
     on mt.sequence like theone.sequence+ '%' or
        theone.sequence like mt.sequence + '%'

但是,例如,您必须小心 101 匹配。因此,让我们在适当的情况下添加一个额外的句点:

select mt.*
from (select sequence from my_table where USER_ID = 53) theone join
     my_table mt
     on mt.sequence like theone.sequence+ '.%' or
        theone.sequence like mt.sequence + '.%'

关于sql - 如何在 SQL Server 中选择父行和子行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15200899/

相关文章:

sql - 在命令行上执行一系列SQL命令

sql - 有没有办法替代 GROUP BY

javascript - 使用 Javascript 转换 JSON 日期

javascript - jQuery : How to check if NO option was explicitly selected in a select box

performance - 为什么 SQLite 3.7.2 在 Step 操作上比 3.7.9 快 3 倍

sql - 为什么 dbms_random.value 在图形查询(连接依据)中返回相同的值?

java - Spring-Data-JPA throws "Caused by: java.sql.SQLException: Incorrect syntax near ' limit'."by using findAll

sql - 需要来自更复杂查询的 COUNT

python - 在点距条件下选择行

sql - Netezza 聚合问题(枢轴)