2016-06-16 69 views
0

我嘗試查找給定父項的所有子項和子子項,但如果使用WHILE循環則無法獲得所需的輸出項。令人驚訝的是,如果我手動執行腳本,它會按預期工作。請看下面的腳本。WHILE循環插入不按預期方式工作

DROP TABLE IF EXISTS test; 
CREATE TABLE test (id INT, parent_id INT); 
INSERT INTO test VALUES (1,NULL); 
INSERT INTO test VALUES (2,1); 
INSERT INTO test VALUES (3,2); 
INSERT INTO test VALUES (4,2); 
INSERT INTO test VALUES (5,3); 
INSERT INTO test VALUES (6,4); 
INSERT INTO test VALUES (7,2); 
INSERT INTO test VALUES (8,4); 
INSERT INTO test VALUES (9,1); 
INSERT INTO test VALUES (10,1); 
COMMIT; 

DELIMITER $$ 

USE `test`$$ 

DROP PROCEDURE IF EXISTS `get_parent_child_hierarchy`$$ 

CREATE PROCEDURE `get_parent_child_hierarchy`(Parent_ID INT) 
BEGIN 

DECLARE `rowcount` INT DEFAULT 1; 

DROP TABLE IF EXISTS Temp; 

CREATE TABLE Temp(ParentID INT, ChildID INT, Stage INT); 


INSERT INTO Temp(ParentID, ChildID, Stage) 
SELECT Parent_ID, Parent_ID, 2; 

WHILE rowcount > 0 DO 

    UPDATE Temp 
    SET Stage = 1 
    WHERE Stage = 2; 
    COMMIT; 

    INSERT INTO Temp(ParentID, ChildID, Stage) 
    SELECT Parent_ID, id, 2 
    FROM Test T 
    WHERE Parent_id IN (SELECT ChildID 
         FROM Temp 
         WHERE Stage = 1 
         AND Temp.ChildID <> T.id); 


    UPDATE Temp 
    SET Stage = 0 
    WHERE Stage = 1; 
    COMMIT; 

    SET rowcount = (SELECT COUNT(ChildID) 
        FROM Temp 
        WHERE Stage = 2); 

END WHILE; 


SELECT * 
FROM Temp 
WHERE Parent_ID <> ChildID; 

DROP TABLE IF EXISTS Temp; 

END$$ 

DELIMITER ; 

輸入:2

預期輸出:

ParentID | ChildID | Stage 
---------|---------|------ 
    2 | 3 | 0 
    2 | 4 | 0 
    2 | 5 | 0 
    2 | 6 | 0 
    2 | 7 | 0 
    2 | 8 | 0 

但不幸的是,在使用WHILE循環腳本運行,我得到了輸入的所有行。

任何幫助表示讚賞。

我同意這是比技術問題更具體的問題。但是我不知道MySQL是否有任何問題,當你使用WHILE循環和INSERT時。

回答

1

您將輸入參數的名稱定義爲Parent_ID,這是表test中的一列,這是您沒有得到預期結果的原因。

嘗試以下;)

CREATE PROCEDURE `get_parent_child_hierarchy`(pid INT) 
BEGIN 

DECLARE `rowcount` INT DEFAULT 1; 

DROP TABLE IF EXISTS Temp; 

CREATE TABLE Temp(ParentID INT, ChildID INT, Stage INT); 


INSERT INTO Temp(ParentID, ChildID, Stage) 
SELECT pid, pid, 2; 

WHILE rowcount > 0 DO 

    UPDATE Temp 
    SET Stage = 1 
    WHERE Stage = 2; 
    COMMIT; 

    INSERT INTO Temp(ParentID, ChildID, Stage) 
    SELECT pid, id, 2 
    FROM test T 
    WHERE parent_id IN (SELECT ChildID 
         FROM Temp 
         WHERE Stage = 1 
         AND Temp.ChildID <> T.id); 


    UPDATE Temp 
    SET Stage = 0 
    WHERE Stage = 1; 
    COMMIT; 

    SET rowcount = (SELECT COUNT(ChildID) 
        FROM Temp 
        WHERE Stage = 2); 

END WHILE; 


SELECT * 
FROM Temp 
WHERE pid <> ChildID; 

DROP TABLE IF EXISTS Temp; 

END 
+0

這果然奏效。謝謝@Reno –

相關問題