mysql cursor - 在语句中选择ID

时间:2014-04-01 08:21:13

标签: mysql cursor

  

它将ID作为字符串返回,它只返回一个具有第一个ID的行。 “7,6,5”只返回7;我们怎样才能纠正这个问题?

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

1 个答案:

答案 0 :(得分: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;