0

我以与此答案类似的方式使用闭包表。我有以下两个表:

CREATE TABLE `part` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

哪个是保存数据的表。

CREATE TABLE `BOM` (
  `ancestor_id` int(11) NOT NULL,
  `descendant_id` int(11) NOT NULL,
  `quantity` int(11) DEFAULT NULL,
  `length` int(11) DEFAULT NULL,
  PRIMARY KEY (`ancestor_id`,`descendant_id`),
  KEY `fk_BOM_part1_idx` (`ancestor_id`),
  KEY `fk_BOM_part2_idx` (`descendant_id`),
  CONSTRAINT `fk_BOM_part1` FOREIGN KEY (`ancestor_id`) REFERENCES `part` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_BOM_part2` FOREIGN KEY (`descendant_id`) REFERENCES `part` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这是关闭表。它使用列长度来记录您在树中的深度。这是我正在使用的测试数据:

INSERT INTO `BOM` (`ancestor_id`, `descendant_id`, `quantity`, `length`) VALUES (1,1,3,0),(3,1,3,1),(3,3,1,0),(4,1,7,1),(4,4,1,0);
INSERT INTO `part` (`id`, `name`, `part_type_id`) VALUES (1,'A',1),(2,'B',1),(3,'1',1),(4,'2',1);

在每个孩子只有一个父母的情况下,以下查询以正确的顺序输出整个树:

select 
    part.id AS id,
    concat(repeat('-', MAX(tree.length)), part.name) as name,
    group_concat(distinct tree.quantity) as quantity,
    group_concat(tree.ancestor_id order by tree.length desc separator ',') as breadcrumbs
from part
    join BOM tree on
        part.id = tree.descendant_id
    group by part.id
    order by breadcrumbs;

但是,当数据库中有同一个孩子的多个父母时,这不起作用。我得到的是:

1
2
-A

我想要的是:

1
-A
2
-A

我明白为什么会发生这种情况,但我不知道如何解决它。我应该使用什么查询以正确的顺序拉动整个树?

4

0 回答 0