prepare语句将逗号分隔值传递给存储过程参数

时间:2014-08-26 14:42:43

标签: mysql sql database stored-procedures

我无法将查询移动到商店过程中。我需要将逗号分隔的字符串传递给参数yr_model_no以获取两个IN子句。我已阅读了几个主题并决定使用prepare语句。原始查询可以正常获取多行,但在存储过程中,当我使用call load_things('1283943kd9,2e9kk389334','53')调用它时(第一个是模型编号列表,第二个是用户ID),它只能获取一行从逗号分隔字符串的第一个值开始。起初,我认为这是yr_model_no参数的长度问题,但将其更改为varchar(200)会在'where子句'错误中给出未知列2e9kk389334。有人可以帮我弄清楚以下代码中的prepare语句或参数有什么问题吗?

这是我的表架构和查询的similar fiddle example

DELIMITER ;;
CREATE PROCEDURE `load_things` (IN `yr_model_no` varchar(20), IN `yr_app_id` int(5))
BEGIN
    SET @s = 

CONCAT('
SELECT * FROM 
(
   SELECT COUNT( c.app_id ) AS users_no, ROUND( AVG( c.min ) , 1 ) AS avg_min, ROUND( AVG( c.max ) , 1 ) AS avg_max, a.mid, a.likes, a.dislikes, b.model_no
        FROM  `like` a
        RIGHT JOIN  `model` b ON a.mid = b.mid
        LEFT JOIN  `details` c ON c.mid = b.mid
        WHERE b.model_no IN (',yr_model_no,')
        GROUP BY b.model_no
)TAB1
JOIN
(
   SELECT a.app_id,b.model_no,IFNULL(c.isbooked,0) AS isbooked,d.min,d.max,e.like_type
     FROM `users` a
     JOIN `model` b
       ON b.model_no IN (',yr_model_no,')
LEFT JOIN `favorite` c 
       ON c.app_id = a.id
      AND c.mid = b.mid         
LEFT JOIN `details` d 
       ON d.app_id = a.id
      AND d.mid = b.mid 
LEFT JOIN `users_likes` e
       ON e.app_id = a.id
      AND e.mid = b.mid
    WHERE a.id = ',yr_app_id,'
)TAB2
ON TAB1.model_no = TAB2.model_no');

PREPARE stmt from @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt3;
END;;
DELIMITER ;

1 个答案:

答案 0 :(得分:1)

如果您考虑您的语句生成的SQL,它将如下所示

JOIN `model` b
ON b.model_no IN (1283943kd9,2e9kk389334)

这是无效的SQL(您需要围绕varchar值引用)

您需要确保在传递给过程的字符串中的每个值周围添加引号:

load_things('''1283943kd9'',''2e9kk389334''','53')

不确定这是否是在MySQL中转义字符串的正确方法(您可能需要查看文档)

这将导致:

JOIN `model` b
ON b.model_no IN ('1283943kd9','2e9kk389334')