我創建了一個表tbl_person來覆蓋id,name和parent_id,以實現從孩子到父母的1:n關係,所以父母孩子都在一張桌子裏! CREATE TABLE `tbl_person` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` int(11) unsigned DEFAULT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `fk_parent_person` (`parent_id`),
CONSTRAINT `fk_parent_person` FOREIGN KEY (`parent_id`)
REFERENCES `tbl_person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE tbl_input(parent VARCHAR(20),childs VARCHAR(200));
INSERT INTO tbl_input(parent,childs) VALUES
('parent','child,children'),
('jane','jane1,jane2'),
('denise','denise1,denise2,denise3'),
('lovely','lovely1');
功能str_split和程序Input2person的定義:: (我從this answer改編)
DELIMITER $$
CREATE FUNCTION strSplit(x VARCHAR(20000), delim VARCHAR(12), pos INTEGER)
RETURNS VARCHAR(20000)
BEGIN
DECLARE output VARCHAR(20000);
SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos)
, LENGTH(SUBSTRING_INDEX(x, delim, pos - 1)) + 1)
, delim
, '');
IF output = '' THEN SET output = null; END IF;
RETURN output;
END $$
CREATE PROCEDURE Input2person()
BEGIN
DECLARE i INTEGER;
INSERT INTO tbl_person (name) SELECT parent FROM tbl_input;
SET i = 1;
REPEAT
INSERT INTO tbl_person (name,parent_id)
SELECT strSplit(c.childs, ',', i), p.id
FROM tbl_input c JOIN tbl_person p ON c.parent = p.name
WHERE strSplit(c.childs, ',', i) IS NOT NULL;
SET i = i + 1;
UNTIL ROW_COUNT() = 0
END REPEAT;
END $$
DELIMITER ;
tbl_person,tbl_input和一些樣品數據的