MySQL选择同一表中由ID链接的所有行
我有一个包含以下字段的表: 父项引用同一表中的主键ID,而不是外键MySQL选择同一表中由ID链接的所有行,mysql,Mysql,我有一个包含以下字段的表: 父项引用同一表中的主键ID,而不是外键 +----+--------+------------+ | ID | Parent | Title | +----+--------+------------+ | 1 | 0 | Wallpapers | | 2 | 1 | Nature | | 3 | 2 | Trees | | 4 | 3 | Leaves | +----+-------
+----+--------+------------+
| ID | Parent | Title |
+----+--------+------------+
| 1 | 0 | Wallpapers |
| 2 | 1 | Nature |
| 3 | 2 | Trees |
| 4 | 3 | Leaves |
+----+--------+------------+
我正在尝试选择一行及其所有父行。例如,如果我选择树叶,我想得到树、自然和墙纸,因为这是层次结构上的父路径。这在一个查询中可能吗?目前,我正在使用ColdFusion中的一个循环来获取每次迭代的下一个父级,但效率不够。试试这个
SELECT
DISTINCT c.id AS 'ID', c.title AS 'Name'
FROM YourTable c, YourTable p
WHERE c.id = p.parent AND c.title = 'Leaves'
使用联合将返回主行的查询与另一个返回父行的查询组合起来
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")
您必须使用自联接来实现这一点:-
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'
在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;
}
如果选择Nature,输出应该是什么?Nature应该返回墙纸,因为Nature的父项是1,1是墙纸。它不应该继续查找同一个记录的所有家长。这是用于相册的,所以可以将其视为彼此内部的递归相册,因此,如果我在相册自然中,则父相册是墙纸等。为什么树叶返回自然和树木?叶子的父项是1,这就是墙纸。使用并集将返回主行的查询与返回其父项的查询结合起来。这只返回一个父项,而不是一个记录的所有父项。我想这就是您想要的:它不应该前进并查找该记录的所有父项。您想要的是父项、祖父母,曾祖父母,等等?我的意思是,如果我选择了像树这样的东西,我不想让它长出叶子,只要它之前的东西有意义。你说你是对的,叶子应该还树。