MySQL:在WHERE IN子句中使用变量

时间:2010-12-14 12:36:54

标签: mysql variables

我试图使用从GROUP_CONCAT获取的值的“数组”到WHERE IN语句中变得疯狂,当GROUP_CONCAT只接受一个“id”时它工作正常但是当它需要更多时它不会。

如下:

START TRANSACTION;
DECLARE @coupon_ids VARCHAR(MAX);
-- Take one or more ids
SET @coupon_ids:=(SELECT IFNULL( (SELECT GROUP_CONCAT(coupon_id) FROM some_table WHERE order_id=(SELECT entity_id FROM sales_order WHERE increment_id=310033638) GROUP BY order_id),  (SELECT coupon_id FROM some_table WHERE coupon_id=310033638)));
SELECT @coupon_ids;
INSERT INTO some_table_gift VALUES (NULL,TRIM('whatever'),'','');
SET @lastid:=LAST_INSERT_ID();
-- Here if @coupon_ids is just one id, like 123 it works, if it is a list of them like 123,234,254 it doesn't works
UPDATE some_table SET owner_id=@lastid,is_gift=1 WHERE coupon_id IN (@coupon_ids);
COMMIT;
-- Same here
SELECT coupon_id,owner_id,is_gift FROM some_table WHERE coupon_id IN (@coupon_ids);

有谁知道如何使用它?

谢谢!

1 个答案:

答案 0 :(得分:0)

对于coupon_id,您的归档类型是什么,如果它不是任何数字类型,那么它将不起作用。

您可以在GROUP_CONCAT写入

中为每个结果添加引号(单引号)的一种方法
GROUP_CONCAT(coupon_id SEPARATOR '","')

删除SELECT @coupon_ids

并且

在QUERY中尝试此WHERE coupon_id IN ("@coupon_ids")