AWS RDS MySQL - GROUP_CONCAT 返回多行而不是逗号分隔的字符串
Posted
技术标签:
【中文标题】AWS RDS MySQL - GROUP_CONCAT 返回多行而不是逗号分隔的字符串【英文标题】:AWS RDS MySQL - GROUP_CONCAT returns multiple rows instead of comma separated string 【发布时间】:2018-10-23 06:57:03 【问题描述】:我有一个Stored Procedure
,它接受三个参数,其中一个是TEXT
,它应该包含ids
的逗号分隔值,类似这样-> '12345,54321,11111,22222'
,它插入一行数据对于列表中的每个 id。下面是Stored Procedure
:
DELIMITER //
-- Create Stored Procedure
CREATE PROCEDURE MyProcedure(
IN ItemUUID VARCHAR(255),
IN ReceiverIds TEXT,
IN ItemCreated VARCHAR(255)
)
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE SubStrLen INT DEFAULT 0;
IF ReceiverIds IS NULL THEN
SET ReceiverIds = '';
END IF;
do_this:
LOOP
SET strLen = LENGTH(ReceiverIds);
INSERT INTO item_receiver (item_uuid, receiver_id, item_created)
VALUES (ItemUUID ,SUBSTRING_INDEX(ReceiverIds, ',', 1),ItemCreated);
SET SubStrLen = LENGTH(SUBSTRING_INDEX(ReceiverIds, ',', 1)) + 2;
SET ReceiverIds = MID(ReceiverIds, SubStrLen, strLen);
IF ReceiverIds = '' THEN
LEAVE do_this;
END IF;
END LOOP do_this;
END//
DELIMITER ;
要使用ids
获取逗号分隔值,类似这样-> '12345,54321,11111,22222'
我执行subquery
,但是,当我调用它Stored Procedure
时出现此错误-> Error Code: 1242. Subquery returns more than 1 row
SET group_concat_max_len = 2048;
call MyProcedure('random_test_uuid',(
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
GROUP BY receiver_id ),
'2017-09-24 23:44:32');
【问题讨论】:
【参考方案1】:问题是子查询。删除group by
:
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids
FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
使用group by
,您会为每个receiver_id
获得一个单独的行。 group_concat()
没有做任何事情。
另外,CAST()
是不必要的。这通常会写成:
SELECT GROUP_CONCAT(r.receiver_id SEPARATOR ',') AS receiver_ids
FROM receiver r JOIN
user u
ON u.user_id = r.user_id
WHERE u.user_name LIKE 'myName';
如果'myName'
没有使用通配符,那么=
比like
更合适。
如果receiver_id
在receiver
中不是唯一的,那么您可能需要将distinct
添加到group_concat()
。
【讨论】:
以上是关于AWS RDS MySQL - GROUP_CONCAT 返回多行而不是逗号分隔的字符串的主要内容,如果未能解决你的问题,请参考以下文章
从 MySQL 客户端通过 AWS 堡垒主机连接到 MySQL RDS 实例