How to use the MySqlGroup_concat() function.

Asked 2 years ago, Updated 2 years ago, 34 views

Hi, everyone.

Shoveling now because of group_concat().

First of all,

select 
    group_concat(cu1.cu_inflow_type),count(cu1.cu_inflow_type)
    from cu_test cu1
    left join cu_test cu2
    on cu2.seq=cu1.seq
    group by cu1.cu_inflow_type 

Results:

======================================================================
group_concat(cu1.cu_inflow_type)    |    count(cu1.cu_inflow_type)
----------------------------------------------------------------------
001,001,001,001,001,001,001,00..    | 27
002,002                             | 2
003,003                             | 2 
004,004,004                         | 3
005                                 | 1
006                                 | 1
----------------------------------------------------------------------

This is the basic result.

The results I want are as follows

======================================================================
group_concat(cu1.cu_inflow_type)    |    count(cu1.cu_inflow_type)
----------------------------------------------------------------------
001,001,001,001,001,001,001,00..    | 27
002,002,003,003 | 4 <-- 002 and 003 merge
004,004,004                         | 3
005,006 | 2 <-- 005 and 006 merge
----------------------------------------------------------------------

I want to print this out. But I don't know what to do. ㅠ<

php htm mysql

2022-09-21 20:31

1 Answers

Assuming that the cu_inflow_type will no longer change to enumerated, I think we can do the following:

SELECT 
    group_concat(cu1.cu_inflow_type),count(cu1.cu_inflow_type)
FROM cu_test cu1
  LEFT JOIN cu_test cu2
    ON cu2.seq=cu1.seq
GROUP BY (CASE
            WHEN  cu1.cu_inflow_type  = '003' THEN '002'
            WHEN  cu1.cu_inflow_type  = '006' THEN '005'
            ELSE cu1.cu_inflow_type 
          END)

In the GROUP BY section, if cu_inflow_type is 003, the value is treated as 002 for grouping as 002, and the value of 006. Other values are to be GROUP by making the original values.

The above method is possible when the cu_inflow_type mentioned in the question is limited, and if it increases more, a separate table is needed to express homogeneity when the cu_inflow_type value is GROUP.


2022-09-21 20:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.