我遇到使用mysql进行多级页面查询的问题。
我的表结构是这样的。表名是'default_pages'
id title parent_id
18 About Us 0
19 ab 1 18
20 contact 0
21 ab 2 18
22 sub 1 21
23 sub 2 22
我的查询是
SELECT p.id AS id, p.title AS ptitle, parent.id AS parent, grandparent.id AS grandparent
FROM default_pages AS p
LEFT JOIN default_pages AS parent ON p.parent_id = parent.id
LEFT JOIN default_pages AS grandparent ON parent.parent_id = grandparent.id
where p.parent_id = 18
但我得到以下输出
id ptitle parent grandparent
19 ab 1 18 null
21 ab 2 18 null
所需的输出应为
id ptitle parent grandparent
19 ab 1 18 null
21 ab 2 18 null
22 sub 1 21 18
23 sub 2 22 21
答案 0 :(得分:1)
不幸的是,MySQL并不直接支持分层或递归查询,因此您必须使用固定数量的多个连接(或使用存储过程)来处理此问题。我想你想检查所有父ID中的18
:
SELECT p.id AS id, p.title AS ptitle, parent.id AS parent, grandparent.id AS grandparent
FROM default_pages p LEFT JOIN
default_pages parent
ON p.parent_id = parent.id LEFT JOIN
default_pages grandparent
ON parent.parent_id = grandparent.id
WHERE 18 in (p.parent_id, parent.parent_id, grandparent.parent_id);
答案 1 :(得分:0)
错误发生在where子句中,它将结果限制为parent_id = 18的所有行。相反,您似乎希望所有具有父级的行。这应该有效:
SELECT p.id AS id, p.title AS ptitle, parent.id AS parent, grandparent.id AS grandparent
FROM default_pages AS p
LEFT JOIN default_pages AS parent ON p.parent_id = parent.id
LEFT JOIN default_pages AS grandparent ON parent.parent_id = grandparent.id
where p.parent_id != 0