简体   繁体   English

Mysql选择以查看层次结构

[英]Mysql select to view Hierarchy

I am developing a way to store files using php & mysql. 我正在开发一种使用php和mysql存储文件的方法。 I am hitting a "mind freeze" with this piece of SQL 我在这段SQL中遇到了“思想冻结”

So, i have this table: 所以,我有这张桌子:

IDIGORDISKFOLDER   NAME       PARENT
1                  |/             |(null)
6                  |subfolderl2   |2
3                  |/             |(null)
4                  |pics          |1
5                  |/             |0
6                  |subfolderl2   |2
7                  |subfolderl3   |6

And I am trying to get Something like this: getting parents for id number 7 我正在尝试得到这样的东西:让父母获得身份证号码7

IDIGORDISKFOLDER   NAME       PARENT
7                  |subfolder13   |6
6                  |subfolderl2   |2
6                  |subfolderl2   |2
1                  |/             |(null)

After some extensive search, I've created the following (SQL) code: 经过广泛的搜索,我创建了以下(SQL)代码:

DROP PROCEDURE IF EXISTS getTopParents;
delimiter //
DROP PROCEDURE IF EXISTS getTopParents;
CREATE PROCEDURE getTopParents(in someId int)
BEGIN
declare pid int default NULL;
SELECT parent into pid from igorDiskFolder WHERE idigorDiskFolder = someId;
    if (pid is not NULL) then
        select idigorDiskFolder, name, parent from igorDiskFolder where idigorDiskFolder = someId;
        CALL getTopParents(pid);
    end if;
END //
delimiter ;

call getTopParents(2);

But, for some reason, I can't get it running. 但是,由于某种原因,我无法使其运行。 The SELECT statements itself are working. SELECT语句本身正在运行。 the "declare" seems to throw an error. “声明”似乎引发了错误。 I've also tried with SET @pid, but with no luck. 我也尝试使用SET @pid,但是没有运气。 If it helps, look at this non-working fiddle: http://sqlfiddle.com/#!2/e3cc6/2 如果有帮助,请查看此无效的小提琴: http ://sqlfiddle.com/#!2/ e3cc6/2

Also, I'd be willing to do this via PHP & MySQL(i), but I don't know if it will affect performance. 另外,我愿意通过PHP和MySQL(i)进行此操作,但我不知道它是否会影响性能。

A fairly standard approach is using @var to keep track of parent: 一个相当标准的方法是使用@var跟踪父级:

select idigorDiskFolder, name, @id := parent parent
from (select * from igorDiskFolder order by parent desc) a
join (select @id := 7) b
where idigorDiskFolder = @id;

fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM