MySQL 中的分层查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8104187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:39:23  来源:igfitidea点击:

Hierarchical queries in MySQL

mysqlhierarchical-data

提问by Quassnoi

I'm trying to find all the parents, grandparents, etc. of a particular field with any depth. For example, given the below structure, if I provide 5, the values returned should be 1, 2, 3 and 4.

我试图找到具有任何深度的特定领域的所有父母、祖父母等。例如,给定下面的结构,如果我提供 5,返回的值应该是 1、2、3 和 4。

| a  | b  |
-----------
| 1  | 2  |
| 2  | 3  |
| 3  | 4  |
| 4  | 5  |
| 3  | 6  |
| 4  | 7  |

How would I do this?

我该怎么做?

回答by Quassnoi

SELECT  @id :=
        (
        SELECT  senderid
        FROM    mytable
        WHERE   receiverid = @id
        ) AS person
FROM    (
        SELECT  @id := 5
        ) vars
STRAIGHT_JOIN
        mytable
WHERE   @id IS NOT NULL

回答by Praxis Ashelin

The following answer is not MYSQL-only, but uses PHP. This answer can be useful for all those that end up on this page during their search (as I did) but are not limited to using MYSQL only.

以下答案不是仅限 MYSQL,而是使用 PHP。这个答案对所有在搜索过程中最终出现在此页面上的人(就像我所做的那样)都很有用,但不仅限于仅使用 MYSQL。

If you have a database with a nested structure of unknown depth, you can print out the contents using a recursive loop:

如果您的数据库具有未知深度的嵌套结构,则可以使用递归循环打印出内容:

function goDownALevel($parent){
     $children = $parent->getChildren(); //underlying SQL function
     if($children != null){
          foreach($children as $child){
                //Print the child content here
                goDownALevel($child);
          }
     }
}

This function can also be rewritten in any other language like Javascript.

此函数也可以用任何其他语言(如 Javascript)重写。