如何获取文件路径的所有父文件夹

时间:2012-05-16 16:42:09

标签: mysql sql

我有一个表格,文件路径为varchar s:

select * from file;
+-------------+
| path        |
+-------------+
| a/b/c/d/e/f |
| a/b/c/x/y   |
+-------------+

我需要获取包含其中一个文件的所有文件夹:

select * from parent_folders;
+-----------+
| parent    |
+-----------+
| a         |
| a/b       |
| a/b/c     |
| a/b/c/d   |
| a/b/c/d/e |
| a/b/c/x   |
+-----------+

我该怎么做?

1 个答案:

答案 0 :(得分:4)

DELIMITER ;;

DROP PROCEDURE IF EXISTS explode_paths;;
CREATE PROCEDURE explode_paths() BEGIN
  DECLARE folders INT DEFAULT 0;
  DECLARE i INT DEFAULT 0;
  DECLARE done BOOLEAN DEFAULT FALSE;
  DECLARE cur CURSOR FOR SELECT path FROM file;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  DROP TEMPORARY TABLE IF EXISTS parent_folders;
  CREATE TEMPORARY TABLE parent_folders (
    parent VARCHAR(255) NOT NULL PRIMARY KEY
  ) ENGINE=Memory;

  OPEN cur;
    read_loop: LOOP
      FETCH cur INTO value;
      IF done THEN
        LEAVE read_loop;
      END IF;

      SET folders = (SELECT LENGTH(value) - LENGTH(REPLACE(value,'/','')));
      SET i=1;
      WHILE i <= folders DO
        INSERT IGNORE INTO parent_folders VALUES (SUBSTRING_INDEX(value,'/',i));
        SET i = i + 1;
      END WHILE;
    END LOOP;

    SELECT * FROM parent_folders;
  CLOSE cur;
END;;

DELIMITER ;