如何从多列table中识别叶节点?
How to identify leaf node from multi column table?
我有一个 table 有多列 category/sub-categories
我想识别作为叶节点的行。叶节点可以在任何级别,例如第 11 个用于连衣裙的节点是叶节点,因为它没有子节点。
我如何在 MS SQL 中实现此目的?
您可以使用 not exists
。 SQL 服务器现在有一个方便的功能 concat_ws()
在这里很有用:
with t as (
select t.*,
concat_ws('->', group_1, group_2, group_3, group_4) as groups
from <table> t
)
select t.*
from t
where not exists (select 1
from t t2
where t2.groups like concat(t.groups, '->%')
);
没有 concat_ws()
也很容易:
with t as (
select t.*,
concat('->' + group_1,
'->' + group_1,
'->' + group_3,
'->' + group_4
) as groups
from <table> t
)
注意:这同时使用 concat()
和 +
,因为它们处理 NULL
值的方式不同。 concat()
忽略 NULL
值,但 +
returns 一个 NULL
值,如果任何参数是 NULL
.
我有一个 table 有多列 category/sub-categories
我想识别作为叶节点的行。叶节点可以在任何级别,例如第 11 个用于连衣裙的节点是叶节点,因为它没有子节点。 我如何在 MS SQL 中实现此目的?
您可以使用 not exists
。 SQL 服务器现在有一个方便的功能 concat_ws()
在这里很有用:
with t as (
select t.*,
concat_ws('->', group_1, group_2, group_3, group_4) as groups
from <table> t
)
select t.*
from t
where not exists (select 1
from t t2
where t2.groups like concat(t.groups, '->%')
);
没有 concat_ws()
也很容易:
with t as (
select t.*,
concat('->' + group_1,
'->' + group_1,
'->' + group_3,
'->' + group_4
) as groups
from <table> t
)
注意:这同时使用 concat()
和 +
,因为它们处理 NULL
值的方式不同。 concat()
忽略 NULL
值,但 +
returns 一个 NULL
值,如果任何参数是 NULL
.