简体   繁体   中英

How do I properly group the following MySql table without losing data?

I want to group the following table that I want to group by RecordId, but I don't want to lose any data. Currently, I was grouping by Email which was keeping all the data.

Id  | RecordId | Email            | Message          | ActionId |
    ----------------------------------------------------------------------
     1  | 2        | john@example.com |  Record inserted |  1       |
     1  | 2        | jane@example.com |  Record Updated  |  2       |
     1  | 2        | joe@example.com  |  Record Deleted  |  3       |

Doing this query resulted in pretty much the same table:

SELECT * FROM Messages
  GROUP BY Email

Doing this query results in 1 record which I know why, but I lost the data from the other records, for example, the Email, Message, and ActionId:

SELECT * FROM Messages
  GROUP BY RecordId

results in

Id  | RecordId | Email            | Message          | ActionId |
    ----------------------------------------------------------------------
     1  | 2        | john@example.com |  Record inserted |  1       |

Is there anyway I can Group By RecordId and still keep all the data. I am trying to create one record based on the RecordId , while keeping all the data so I can send out an email to all the people in the Email Column, but with their respective Message (Record Inserted, Record Deleted, Record Updated) .

Will GROUP_CONCAT() help?

SELECT RecordId, GROUP_CONCAT(CONCAT_WS(",", Email, Message, ActionId) SEPARATOR ";")
FROM Messages GROUP BY RecordId

Note: there is a limit of GROUP_CONCAT() result length. So if you foresee grouping a lot of records, then its not your solution.

The bellowing query will return only one record per RecordID with all the information. (It's a bit ugly thought)

SELECT  RecordId,

        EMAIL = (   SELECT EMAIL + ';'
                    FROM Messages AS M
                    WHERE Messages.RecordId = M.RecordId
                    FOR XML PATH('')),

        [Message] =(SELECT [Message] + ';'
                    FROM Messages AS M
                    WHERE Messages.RecordId = M.RecordId
                    FOR XML PATH('')),

        ActionId =(SELECT ActionId + ';'
                    FROM Messages AS M
                    WHERE Messages.RecordId = M.RecordId
                    FOR XML PATH(''))

FROM Messages
GROUP BY RecordId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM