gpt4 book ai didi

php - 从这样的表中检索层次结构

转载 作者:行者123 更新时间:2023-11-29 01:17:10 25 4
gpt4 key购买 nike

我将 MySql 与 PHP 一起使用,并将我的所有数据都放在这样的表中:

"id"    "name"         "description"               "level"  "parent"    "country"   "maxLevel"
"1" "Kitchenware" "Kitchenware description" "1" "0" "US" "0"
"2" "Knives" "All our knives" "2" "1" "US" "0"
"3" "Butter Knives" "All Butter Knives" "3" "2" "US" "0"
"4" "Cut em all" "Cut em all" "4" "3" "US" "0"
"5" "Cull em all" "Cull em all" "4" "3" "US" "0"
"6" "Smear em all" "Smear em all" "4" "3" "US" "0"
"7" "Meat Knives" "All Meat Knives" "3" "2" "US" "0"
"8" "Cut em meat" "Cut em meat" "4" "7" "US" "0"
"9" "Cull em meat" "Cull em meat" "4" "7" "US" "0"
"10" "Smear em meat" "Smear em meat" "4" "7" "US" "0"

据此,如果我有例如:id = 10,sql 将如何显示项目的层次结构?

所以对于 id = 10,层次结构将是:

Kitchenware > Knives > Meat Knives > Smear em meat

对于 id=7 的层次结构是:

Kitchenware > Knives > Meat Knives

对于 id=4 层次结构将是

Kitchenware > Knives > Butter Knives > Cut em all

等等。知道如何构建 sql 来实现这一点吗?

最佳答案

试试这个存储过程

CREATE PROCEDURE updatePath(in itemId int)
BEGIN
DECLARE cnt int default 0;
CREATE temporary table tmpTable
(
`id` int, `name` varchar(15), `parent` int, path varchar(500)
)engine=memory select id, name, parent, name AS 'Path' from tbl where id = itemId;
select parent into cnt from tmpTable;

while cnt <> 0 do
Update tmpTable tt, tbl t set tt.parent = t.parent,
tt.path = concat(t.name, ' > ', tt.path)
WHERE tt.parent = t.id;
select parent into cnt from tmpTable;
end while;
select * from tmpTable;
drop table tmpTable;
END//

查询 1:

call updatePath(10)

SQL FIDDLE :

| ID |            NAME | PARENT |                                                       PATH |
----------------------------------------------------------------------------------------------
| 10 | "Smear em meat" | 0 | "Kitchenware" > "Knives" > "Meat Knives" > "Smear em meat" |

希望对你有帮助

关于php - 从这样的表中检索层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com