EDIT
làm việc mẫu giải quyết Gordons lưu ý
đường nút Query tính toán như bạn đã cố định độ sâu cây tối đa, và trật tự của nó.
SQL Fiddle
MySQL 5.5.30 Schema Cài đặt:
create table mytable(id int, parent_id int, name varchar(100));
insert mytable(id, parent_id, name)
values (1, null, 'Home'),
(2, null, 'Services'),
(3, 2, 'Baking'),
(4, 3, 'Cakes'),
(5, 3, 'Bread'),
(6, 5, 'Flat Bread'),
(7, 1, 'Something');
Query 1:
select t0.*,
concat(
case coalesce(t4.Parent_ID, 0)
when 0 then ''
else concat(cast(t4.Parent_ID as char), '\\')
end,
case coalesce(t3.Parent_ID, 0)
when 0 then ''
else concat(cast(t3.Parent_ID as char), '\\')
end,
case coalesce(t2.Parent_ID, 0)
when 0 then ''
else concat(cast(t2.Parent_ID as char), '\\')
end,
case coalesce(t1.Parent_ID, 0)
when 0 then ''
else concat(cast(t1.Parent_ID as char), '\\')
end,
case coalesce(t0.Parent_ID, 0)
when 0 then ''
else concat(cast(t0.Parent_ID as char), '\\')
end,
cast(t0.id as char)
) as path
from mytable t0
left join mytable t1 on t0.Parent_ID = t1.Id
left join mytable t2 on t1.Parent_ID = t2.Id
left join mytable t3 on t2.Parent_ID = t3.Id
left join mytable t4 on t3.Parent_ID = t4.Id
order by
concat(
case coalesce(t4.Parent_ID, 0)
when 0 then ''
else concat(cast(t4.Parent_ID as char), '\\')
end,
case coalesce(t3.Parent_ID, 0)
when 0 then ''
else concat(cast(t3.Parent_ID as char), '\\')
end,
case coalesce(t2.Parent_ID, 0)
when 0 then ''
else concat(cast(t2.Parent_ID as char), '\\')
end,
case coalesce(t1.Parent_ID, 0)
when 0 then ''
else concat(cast(t1.Parent_ID as char), '\\')
end,
case coalesce(t0.Parent_ID, 0)
when 0 then ''
else concat(cast(t0.Parent_ID as char), '\\')
end,
cast(t0.id as char)
)
Results:
| ID | PARENT_ID | NAME | PATH |
-----------------------------------------
| 1 | (null) | Home | 1 |
| 7 | 1 | Something | 1\7 |
| 2 | (null) | Services | 2 |
| 3 | 2 | Baking | 2\3 |
| 4 | 3 | Cakes | 2\3\4 |
| 5 | 3 | Bread | 2\3\5 |
| 6 | 5 | Flat Bread | 2\3\5\6 |
Không chắc chắn nếu đây là ý của bạn, nhưng tôi nghĩ điều này sẽ giúp: http://stackoverflow.com/questions/6240028/select-parent-and-children-with-mysql – We0
Bạn đang nói về đệ quy liệt kê một cây theo thứ tự id? MySQL không hỗ trợ điều đó, cuối cùng tôi đã kiểm tra. PostgreSQL, Oracle và SQL Server đã thực hiện thông qua CTE đệ quy. Cách duy nhất tôi biết làm thế nào để làm điều đó với mysql là thực hiện nhiều cuộc gọi đến cơ sở dữ liệu thông qua khách hàng của bạn, tham khảo tập kết quả cuối cùng. –
@ We0 Điều này chỉ giải quyết 2 cấp độ (phụ huynh và trẻ em trực tiếp) –