-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 に答える