-1

我有一个文件路径为varchars 的表:

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   |
+-----------+

我该怎么做呢?

4

1 回答 1

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 ;
于 2012-05-16T17:14:48.127 回答