【问题标题】:group_concat creates a issue for fetching more then one recordgroup_concat 创建了一个获取多于一条记录的问题
【发布时间】:2023-03-29 14:29:01
【问题描述】:

我遇到了一个与 group_concat 相关的问题,因为当我使用它时,无法从基于 transactionID 的表中获取总记录 这是我的存储过程代码。在此,我使用了一个名为 strSplit 的拆分函数。

BEGIN

DECLARE iCount int;

DECLARE i int;

DECLARE txn VARCHAR(65000);

DECLARE txId VARCHAR(17);

CREATE TEMPORARY TABLE report_transaction (client_id INT NOT NULL AUTO_INCREMENT, productName VARCHAR(200), itxnId VARCHAR(100),PRIMARY KEY(client_id));

select count(distinct(tt.TxnId)) into iCount from tbl_transaction tt;

SELECT group_concat(distinct((tt.TxnId)) separator ', ') product into txn  from tbl_transaction tt;

SET i=1;

WHILE i<iCount+1 DO

select strSplit(txn, ',', i) into txId;

SELECT RTRIM(LTRIM(txId));

 INSERT INTO report_transaction(productName,itxnId) select group_concat((tt.ProductName) separator ',') products,tt.TxnId from tbl_transaction tt where tt.TxnId= txId;

    SET i = i + 1;

END WHILE;

     SELECT * FROM report_transaction;
     drop table report_transaction;

END

我想要像表格记录一样的结果,但它只显示第一条记录,然后其他字段为空。

【问题讨论】:

    标签: mysql group-concat


    【解决方案1】:

    我认为你想要的可以通过一个查询来完成:

    INSERT INTO report_transaction(productName,itxnId)
        select group_concat((tt.ProductName) separator ',') as products, tt.TxnId
        from tbl_transaction tt
        group by tt.TxnId;
    

    您不需要临时表来存储 ID,也不需要修剪或拆分任何内容。

    一般来说,在适当的时候使用 SQL 查询可以获得更好的性能。

    顺便说一句,如果您确实需要遍历表中的行,那么您应该了解游标。

    【讨论】:

    • 你应该修改你的问题,或者问另一个问题,包括样本数据和结果。
    • 先生,我的问题是函数 group_concat 在 where 条件下生成一次输出如何解决它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多