MySQL选择在同一个表中按ID链接的所有行

时间:2015-09-04 12:11:14

标签: mysql

我有一个包含字段的表:

Parent引用同一个表中的主键ID(不是外键)。

+----+--------+------------+
| ID | Parent |   Title    |
+----+--------+------------+
|  1 |      0 | Wallpapers |
|  2 |      1 | Nature     |
|  3 |      2 | Trees      |
|  4 |      3 | Leaves     |
+----+--------+------------+

我正在尝试选择一行及其所有父项。例如,如果我选择“离开”,我想要获得“树”,“自然”和“壁纸”,因为这是层次结构中的父路径。这可能在一个查询中?目前我在ColdFusion中使用循环来获取每次迭代的下一个父级,但它不够高效。

4 个答案:

答案 0 :(得分:1)

您必须使用自联接来实现此目的: -

 SELECT T1.Title AS CHILD, T2.Title AS PARENT
 FROM YOUR_TABLE T1, YOUR_TABLE T2
 WHERE T1.PARENT = T2.ID
 AND T1.Title = 'Leaves'

答案 1 :(得分:0)

在PHP中,我编写了一个函数,用于检索路由表的所有层次结构(无限深度)。

我认为,在此示例中,您可以看到要查找的查询的SQL语法。除小写字母外,我使用相同的列名。

function get_breadcrumb($route_id) {
    
    //access PDO mysql object instance
    global $db;

    // sanitize route ID
    $route_id = intval($route_id);
    
    // query construction
    $q = "SELECT T2.*
            FROM (
                SELECT
                    @r AS parent_id,
                    (SELECT @r := `parent` FROM `route` WHERE id = parent_id) AS `parent`,
                    @l := @l + 1 AS `depth`
                FROM
                    (SELECT @r := $route_id, @l := 0) vars,
                    `route` T3
                WHERE @r <> 0) T1
            JOIN `route` T2
                ON T1.parent_id = T2.id
            ORDER BY T1.`depth` DESC";
    
    // call query in database
    if($res = $db->query($q)) {
        if($res = $res->fetchAll(PDO::FETCH_ASSOC)) {
            if($size = sizeof($res) > 0) { 
                
                // push results in breadcrumb items array
                $breadcrumb['items']  = $res;
                $breadcrumb['levels'] = $size;
                
                // retrieve only titles
                $titles = array_column($res, 'title');

                // construct html result seperated by '>' or '/'
                $breadcrumb['html']['gt'] = implode(' > ', $titles);
                $breadcrumb['html']['sl'] = implode(' / ', $titles);

                // returns all result (added in SESSION too)
                return $_SESSION['app']['breadcrumb'] = $breadcrumb;
            }
        }
    }
    
    // no result for that route ID
    return false;
}

答案 2 :(得分:-1)

试试这个

SELECT 
      DISTINCT c.id AS 'ID', c.title AS 'Name'
FROM YourTable c, YourTable p 
WHERE c.id = p.parent AND c.title = 'Leaves'

答案 3 :(得分:-1)

使用UNION将返回主行的查询与返回父行的另一个查询组合在一起。

SELECT *
FROM YourTable
WHERE Title = "Leaves"
UNION
SELECT t1.*
FROM YourTable AS t1
JOIN YourTable AS t2 ON t1.id = t2.parent
WHERE t2.Title = "Leaves")