sql-返回由同一表的初始值引用的值

ut6juiuv  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(265)

我肯定以前有人问过这个问题,但我似乎找不到任何有帮助的问题。
下面是一个表格示例:

ID    Name        Parent ID
---------------------------
1     Ice cream   3 
2     Chips       4
3     Sweets      null

我想知道如何编写一个查询 ID=1 ,将返回第1行和第3行。这不需要两个问题就可以了吗?
另外,是否有方法将父级的信息作为自定义列返回?所以,不是返回2行,而是返回 where id=1parent_id=3 添加了?

5jvtdoz2

5jvtdoz21#

你可以用 union all 以及 exists :

select * from mytable where parent_id = 3
union all
select t.* 
from mytable t 
where exists (select 1 from mytable t1 where t1.parent_id = t.id and t.parent_id = 3)

如果要在多个层次结构级别上执行此操作,则通常使用递归查询。accross数据库的语法略有不同(并不是所有数据库都支持递归),但其思想是:

with recursive cte as (
    select * from mytable where parent_id = 3
    union all
    select t.*
    from cte c
    inner join mytable t on t.parent_id = c.id
)
select * from cte
ibps3vxo

ibps3vxo2#

这就是一个直来直去的笨蛋会做的。紧紧抓住某人,让他给一个更好的方法

SELECT ID, Name, Parent_ID
FROM table
WHERE ID = 1

UNION

SELECT ID, Name, Parent_ID
FROM table
WHERE ID = (SELECT Parent_ID FROM table WHERE ID = 1)
cunj1qz1

cunj1qz13#

你在找这样的东西吗

select child.ID, child.Name, parent.ID as ParentId, parent.Name as ParentName
from T child left outer join T parent on parent.Id = child.parent_id;

相关问题