MySQL通过连接获取层次结构的父级数

时间:2019-06-05 13:16:18

标签: mysql sql hierarchical-data nested-sets

我有两个表,表paragraphs代表存在的所有文本块,表documents代表特定网站的顺序。 这是我的桌子:

CREATE TABLE paragraphs (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    title TEXT CHARACTER SET utf8 COLLATE utf8_german2_ci NOT NULL,
    txt TEXT CHARACTER SET utf8 COLLATE utf8_german2_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE documents (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    paragraph INT NOT NULL,
    lft INT NOT NULL,
    rgt INT NOT NULL,
    website INT NOT NULL,
    FOREIGN KEY (paragraph) REFERENCES paragraphs(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我发现了很多用于获取层次结构的查询的解决方案,但没有找到具有两个单独表的层次结构的解决方案。 我尝试了非常不同的想法,这为我提供了一个特定网站的结构(例如id为1的网站):

SELECT DISTINCT p.title
FROM documents as st1
INNER JOIN documents as st2 ON st1.paragraph = st2.paragraph
INNER JOIN paragraphs as p ON st2.paragraph = p.id
WHERE st1.lft BETWEEN st2.lft AND st2.rgt
AND st2.website = 1
ORDER BY st1.lft;

但是现在我尝试获取从所有节点到根的父或母的路径或路由。

例如插入:

INSERT INTO paragraphs (id,title,category)VALUES(11,'Heading 8',2);
INSERT INTO paragraphs (id,title,category)VALUES(12,'Heading 8.1',2);
INSERT INTO paragraphs (id,title,category)VALUES(13,'Heading 8.1.1',2);
INSERT INTO paragraphs (id,title,category)VALUES(14,'Heading 8.1.2',2);
INSERT INTO paragraphs (id,title,category)VALUES(23,'Heading 10',1);

INSERT INTO documents (website,paragraph,lft,rgt)VALUES(1,11,1,8);
INSERT INTO documents (website,paragraph,lft,rgt)VALUES(1,12,2,7);
INSERT INTO documents (website,paragraph,lft,rgt)VALUES(1,13,3,4);
INSERT INTO documents (website,paragraph,lft,rgt)VALUES(1,14,5,6);
INSERT INTO documents (website,paragraph,lft,rgt)VALUES(1,23,9,10);

我找到了一个不带联接的表的解决方案,并尝试针对我的场景修改和组合此解决方案和两个表和联接,但是我的尝试是为所有行赋予0:

SELECT st1para.title, (COUNT(st2para.title) - 1) AS depth
FROM documents AS st1
INNER JOIN paragraphs AS st1para ON st1.paragraph = st1para.id
JOIN documents AS st2 ON st1.paragraph = st2.paragraph
INNER JOIN paragraphs AS st2para ON st2.paragraph = st2para.id
WHERE st1.lft BETWEEN st2.lft AND st2.rgt
GROUP BY st1para.title
ORDER BY st1.lft;

结果:

|    title     |  depth  |
|--------------|---------|
|Heading 8     |    0    |
|Heading 8.1   |    0    |
|Heading 8.1.1 |    0    |
|Heading 8.1.2 |    0    |
|Heading 10    |    0    |

有人可以帮助我创建有效的查询吗? 我不明白为什么这行不通。

0 个答案:

没有答案