我有一个非常基本的单表场景;
tblFamiles
entryID : Int
name: Text
parentID: Int
让我们添加以下行;
entryID : name : parentID
1 : Grandmother Jones : 0
2 : Grandmother Thompson : 0
3 : Mother Jones : 1
4 : Mother Thompson : 2
5 : 1st Daughter Jones : 3
6 : 2nd Daughter Jones : 3
7 : 1st Daughter Thompson : 4
在这里,我们存储了两个家族的三代,琼斯家族和汤普森家族(例如)。我想查询该表,但按 parentID 对结果进行排序(但不只是像普通 old 一样ORDER BY 'parentID' DESC,因此它们是相对顺序的。我想要这样的输出;
SELECT (SOME MAGIC) FROM `tblFamiles`;
entryID : name : parentID
1 : Grandmother Jones : 0
3 : Mother Jones : 1
5 : 1st Daughter Jones : 3
6 : 2nd Daughter Jones : 3
2 : Grandmother Thompson : 0
4 : Mother Thompson : 2
7 : 1st Daughter Thompson : 4
从逻辑上讲,我能看到如何做到这一点的唯一方法是遍历所有 entryID,然后遍历每个 entryID;循环遍历所有其他记录,根据当前 entryID 检查它们的 parentID 字段,并将这些记录带到结果集的顶部,在当前行下。但我看不到如何在 MySQL 中做到这一点。
更新
我在上面使用了家庭作为示例,但我所追求的是一种存储嵌套条目并将它们放在单个查询中的方法,以提高效率。我可以进行多个SELECT查询,但这很难看;
(Pseudo)
SELECT entryID, name WHERE parentID = 0 LIMIT 0,1;
print name;
Sub query:
SELECT entryID, name WHERE parentID = $above-entryID
print name;
(Keep looping through this till the second query returns no results,
then go back to the first query and move onto the next entryID)
第二次更新
您甚至可以忘记该name列甚至存在,我只是以它为例,这里最重要的是entryID,parentID因为这是链接和控制所有内容的两个列。可能有 20 个额外的列 以及name,但它们都围绕entryID和parentID,它只是链接或嵌套(哪个术语更合适)ID。