2014-04-01 42 views
0

它將ID作爲字符串返回,它只返回一個具有第一個ID的行。 「7,6,5」只返回7;我們如何糾正這個問題?mysql光標 - 在工程中選擇ID

CREATE DEFINER=`root`@`localhost` 
PROCEDURE `GET_COMPANION`(IN paramEmployeeId INT) 
BEGIN 
    DECLARE counter INTEGER DEFAULT 0; 
    DECLARE v_finished INTEGER DEFAULT 0; 
    DECLARE v_companion varchar(100) DEFAULT ""; 
    DECLARE v_companion_list varchar(100) DEFAULT ""; 

    -- declare cursor for companion_id 
    DEClARE companion_cursor CURSOR FOR 
     SELECT companion_id FROM employee_has_companion ehc 
     WHERE ehc.employee_id = paramEmployeeId; 

    -- declare NOT FOUND handler 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1; 

    OPEN companion_cursor; 

    get_companion: LOOP 
     FETCH companion_cursor INTO v_companion; 

     IF v_finished = 1 THEN 
      LEAVE get_companion; 
     END IF; 

     -- build companion list 
     SET v_companion_list = CONCAT(v_companion,",",v_companion_list); 
    END LOOP get_companion; 

    CLOSE companion_cursor; 

    SELECT * FROM companion co 
    LEFT JOIN citizenship ci 
     ON co.citizenship_id = ci.citizenship_id 
    WHERE co.companion_id IN(SUBSTRING(v_companion_list, 
             1,LENGTH(v_companion_list)-1)); 
END 

回答

0

您可以使用FIND_IN_SET(str,strlist)檢查字符串的存在,以逗號分隔值的列表。

更改

SELECT * FROM companion co 
    LEFT JOIN citizenship ci 
     ON co.citizenship_id = ci.citizenship_id 
    WHERE co.companion_id IN(SUBSTRING(v_companion_list, 
             1,LENGTH(v_companion_list)-1)); 

SELECT * FROM companion co 
    LEFT JOIN citizenship ci 
     ON co.citizenship_id = ci.citizenship_id 
    WHERE FIND_IN_SET(co.companion_id, v_companion_list) > 0; 
+0

非常感謝你。 – egemen