【问题标题】:Getting all the children (and their children) of a given parent node in a MySQL relational table在 MySQL 关系表中获取给定父节点的所有子节点(及其子节点)
【发布时间】:2021-05-18 11:33:44
【问题描述】:

我有一张这样的桌子:

child:      parent:
0003        0003
20010       0003
15003       0003
20013       20013
1234        20013
0003        20013

我正在寻找一个查询来选择给定父级的子树,包括每个子级的级别,即如果给定的父级是“20013”,则输出必须是:

child: level:
 [1234, 1]
 [0003, 1]
 [20010, 2]
 [15003, 2]

重要细节我不能使用 cte 查询,所以我很乐意使用标准查询的解决方案

附上 NODEJS 中的代码给我带来的结果我只需要在 mysql 过程中执行此操作:

async function getCldLvl(DB, item, sons, level = 0, treetype) {
    level++;
    let ele1;
    if (treetype)
        ele1 = await myq(`use ??; SELECT * FROM trees WHERE TreeType=? AND ParentKey=?;`, [DB, treetype, item]);
    else
        ele1 = await myq(`use ??; SELECT * FROM trees WHERE ParentKey=? AND ItemKey!=ParentKey;`, [DB, item]);
    const elements = ele1[1];
    if (elements.length != 0) {
        let p = [];
        for (let index = 0; index < elements.length; index++) {
            const e = elements[index];
            if (e.ItemKey != e.ParentKey) {
                sons.values.push({"ItemKey":e.ItemKey, "Quantity":e.Quantity, "Level":level});
                p.push(getCldLvl(DB, e.ItemKey, sons, level, e.TreeType));
            }
        }
        await Promise.all(p);
    }
}


let sons = { values: [] };
await getCldLvl(DB, "apple", sons);
console.log(sons);

谢谢:)

【问题讨论】:

  • “我不能使用 cte 查询”是什么意思?你用的是什么版本的 MySQL?
  • 递归 cte 是标准这里。
  • 版本:5.7.3,无法更新版本!
  • 在不使用递归 cte 的情况下,没有 sql 方法可以解决此查询
  • 确定没有办法?我找到了它 (stackoverflow.com/questions/41113828/…) 但这里没有子级别:(

标签: mysql sql tree


【解决方案1】:
CREATE PROCEDURE get_childs ()
BEGIN
CREATE TABLE get_childs_tmp(id INT UNIQUE, level INT) ENGINE = Memory;
INSERT INTO get_childs_tmp SELECT child, 0 FROM test WHERE child = parent;
REPEAT
    INSERT IGNORE INTO get_childs_tmp
    SELECT test.child, get_childs_tmp.level + 1
    FROM get_childs_tmp
    JOIN test ON test.parent = get_childs_tmp.id;
UNTIL !ROW_COUNT() END REPEAT;
SELECT * FROM get_childs_tmp WHERE level > 0;
DROP TABLE get_childs_tmp;
END

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=c5933bfa05414cd68c91c318a727ed6f

【讨论】:

  • 谢谢,但我尝试使用我放在这里的数据,结果不是我想要的dbfiddle.uk/…
  • 我编辑了我的问题,我很乐意提供帮助。
  • @semicolon NodeJS 问题是单独的问题 - 所以创建新主题。如果需要,请参阅此。
  • 问题不在nodejs中我只是附上了在mysql过程中给我带来我需要的结果的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多