2

我的情况:

Table A
(
ID
Parent_Id
TimeStamp
)

根的 Parent_Id 为 null,子项的 Id 是其父亲。

我只是想得到每个表 A 的所有 LAST 孩子。我不想要的父亲和孩子。(最后一个除外)。

是否可以构建一个 SQL 来获得这个?

PS:我在 sql 任何地方 11。也许 ansi sql 可以解决这个问题,我不确定。

编辑:(编辑以提供更多详细信息)我不希望元素的最后一个孩子。

例子:

Id 1 父级 NULL

ID 2 父级 1

ID 3(最后一个孩子)父母 1

Id 4 父级 NULL

ID 5(最后一个孩子)父母 4

我想得到: Id 3 Id 5

4

4 回答 4

4

使用存储功能

create function LastChild(in parent integer)
returns integer
begin
    declare res integer;  
    select top 1 id into res from TableA where parent_id = parent order by timeCol desc;
    return res;
end

选择

select Id, lastchild(id) from TAbleA where parent_id is null

我将研究另一种没有存储功能的解决方案。

编辑:没有存储功能:

select Id, (select top 1 id from TableA childs where parent_id = TableA.id order by timeCol desc) from TableA where parent_id = 0
于 2009-11-20T19:15:43.803 回答
3

如果“最后一个孩子”是指本身没有孩子的项目(通常称为叶级项目),那么应该这样做:

SELECT ID
 from A
 where ID not in (select Parent_Id from A)

相关的子查询版本有点难以理解,但在大表上运行得更快:

SELECT ID
 from A OuterReference
 where not exists (select 1 from A where Parenti_ID = OuterReference.ID)

(“OuterReference”是表 A 的别名)

我使用 SQL Server,但这是非常基本的语法,只需最少的修改即可为您工作。

于 2009-11-20T18:46:52.383 回答
0
select * from a where id not in (select parent_id from table a)

换句话说,从表 a 中选择所有项目的 ID 不是任何其他项目的父 ID。这将为您提供图形的所有叶节点。

编辑:
您的编辑有点混乱,并且 ID 通常不用作排序机制,但无论如何,您提供的示例可以通过此查询完成

SELECT MAX( id )
FROM a
WHERE id NOT IN
  (SELECT parent_id
      FROM a
      WHERE parent_id IS NOT NULL
  )
GROUP BY parent_id
于 2009-11-20T18:46:45.657 回答
0

对于 Postgres 9.4,我必须稍微更新查询以获取子类别

select count(id) from A as outer_ref where not exists(
    select 1 from A where parent_id=outer_ref.id) and parent_id is not null;
于 2021-05-04T10:38:14.737 回答