代码之家  ›  专栏  ›  技术社区  ›  niko85

AWS RDS MySQL-GROUP\u CONCAT返回多行,而不是逗号分隔的字符串

  •  0
  • niko85  · 技术社区  · 6 年前

    我有一个 Stored Procedure 这需要三个参数,其中一个是 TEXT 它应该包含逗号分隔的值 ids ,类似于此-> '12345,54321,11111,22222' ,它将插入一行,其中包含列表中每个id的数据。以下是 存储过程 :

    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 ,类似于此-> '12345543211111122222' 我执行 subquery 然而,当我称之为 存储过程 我收到此错误-> 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 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    问题是子查询。删除 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') 
    

    使用 分组依据 ,您将为每个 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\u id 在中不是唯一的 receiver ,则可能需要添加 distinct group\u concat()