我会用什么查询来获取同级记录使用封表时?(What query would I use to obt

2019-10-19 11:01发布

如果我有下面的架构和数据,并使用我关闭表模式:

+----+----------+------------+--------+ | id | ancestor | descendant | length | +----+----------+------------+--------+ | 1 | 2 | 2 | 0 | | 2 | 2 | 12 | 1 | | 3 | 2 | 13 | 1 | | 4 | 2 | 14 | 1 | | 5 | 2 | 15 | 1 | | 10 | 12 | 12 | 0 | | 11 | 13 | 13 | 0 | | 12 | 14 | 14 | 0 | | 13 | 15 | 15 | 0 | | 9 | 17 | 20 | 1 | | 8 | 17 | 19 | 1 | | 7 | 17 | 18 | 1 | | 6 | 17 | 17 | 0 | | 14 | 18 | 18 | 0 | | 15 | 19 | 19 | 0 | | 16 | 20 | 20 | 0 | +----+----------+------------+--------+

什么将我加入查询回到我的主表模样,以获得行ID的所有兄弟行2

+----+----------+------------+--------+ | id | ancestor | descendant | length | +----+----------+------------+--------+ | 3 | 2 | 13 | 1 | | 4 | 2 | 14 | 1 | | 5 | 2 | 15 | 1 | +----+----------+------------+--------+

Answer 1:

给定节点的兄弟姐妹也有同样的祖先。 然而,这将包括“1”,以及你的列表:

select t.*
from table t 
where t.ancestor = (select ancestor from table t2 where t.id = 2);

在你的桌子,我不知道这是什么意思为ancestor是一样的descendant 。 但是,我认为以下是您要查询:

select t.*
from table t 
where t.ancestor = (select ancestor from table t2 where t2.id = 2) and
      t.ancestor <> t.descendant and
      t.id <> 2;

编辑:

你可以做到这一点作为一个明确的加入是这样的:

select t.*
from table t join
     table t2
     on t.ancestor = t2.ancestor and
        t2.id = 2 a
where t.id <> 2 and
      t.ancestor <> t.descendant;

注意:我还添加条件t.id <> 2 ,以便“2”不被认为是其自身的兄弟节点。



文章来源: What query would I use to obtain sibling records when using closure tables?