T-SQL 当子记录也是它自己的父记录时,如何排除它?
T-SQL How to exclude a child record when it's also it's own parent record?
我有如下情况:
create table #Example (
id int
, overall_id int
, parent_id int
, child_id int
);
insert into #Example values
(1, 25963, 491575090, 491575090)
,(2, 25963, 547952026, 491575090)
,(3, 25963, 547952026, 230085039)
,(4, 25963, 547952026, 547952026);
select e.*
from #Example as e;
drop table #Example;
我想排除 ID 为“2”的记录,因为那是它自己的父记录(参见 ID“1”)。
我不想排除 3,因为子记录不是它自己的父记录。而且我不想排除 1 和 4,因为它们是它们自己的父记录。
一个问题是,在我的业务场景中,我没有相应的“ID”字段,这是我在本例中提供的,以便我可以唯一地引用每一行。
对于排除记录 2 的技术的任何帮助,我们将不胜感激!
题还是没看懂,但是预期的结果落在了:
select *
from #Example as E
where not exists (
select 42
from #Example as IE
where
-- There is a row that is self parenting?!
IE.parent_id = IE.child_id and
-- The row under consideration is related in a child/parent way?
IE.child_id = E.child_id and
-- It isn't the same row as we're considering.
IE.id <> E.id );
见dbfiddle。
我有如下情况:
create table #Example (
id int
, overall_id int
, parent_id int
, child_id int
);
insert into #Example values
(1, 25963, 491575090, 491575090)
,(2, 25963, 547952026, 491575090)
,(3, 25963, 547952026, 230085039)
,(4, 25963, 547952026, 547952026);
select e.*
from #Example as e;
drop table #Example;
我想排除 ID 为“2”的记录,因为那是它自己的父记录(参见 ID“1”)。
我不想排除 3,因为子记录不是它自己的父记录。而且我不想排除 1 和 4,因为它们是它们自己的父记录。
一个问题是,在我的业务场景中,我没有相应的“ID”字段,这是我在本例中提供的,以便我可以唯一地引用每一行。
对于排除记录 2 的技术的任何帮助,我们将不胜感激!
题还是没看懂,但是预期的结果落在了:
select *
from #Example as E
where not exists (
select 42
from #Example as IE
where
-- There is a row that is self parenting?!
IE.parent_id = IE.child_id and
-- The row under consideration is related in a child/parent way?
IE.child_id = E.child_id and
-- It isn't the same row as we're considering.
IE.id <> E.id );
见dbfiddle。