2017-08-09 85 views
0

如何在mysql中插入多個具有多個孩子的父母?有多個父母和孩子的MySql多重插入

例如:

parent - child/children 
jane - jane1,jane2 
denise - denise1,denise2,denise3 
lovely - lovely1 

-parent插入

insert into tbl_parent(id,name) 
    values('1', 'jane'), ('2', 'denise'), ('3', 'lovely') 

柴爾德插入

回答

0

即使你的問題是不完整的和猜測是喜歡看水晶球,我做了一些假設:

  • 我把你的例子放在一張表中tbl_input
  • 我創建了一個表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和一些樣品數據的

表定義

現在你必須CALL Input2Person();SELECT * FROM tbl_person;以獲得您的結果。希望有所幫助。

相關問題