如何从相同的 table (MYSQL) 重组 groupBy 的值?

How to reorganise the values of a groupBy from the same table (MYSQL)?

我有这样的 Chats table 设置:

ID CHAT_GROUP_ID MESSAGE READ CREATED_AT
1 uu-34uu5-6662 hi1 1 2022-06-02 13:16:42
2 uu-34uu5-6662 hi2 1 2022-06-02 13:16:45
3 uu-34uu5-6663 hi3 0 2022-06-02 13:16:46
4 uu-34uu5-6663 hi4 0 2022-06-02 13:16:47
5 uu-34uu5-6664 hi5 0 2022-06-02 13:16:49
ID = int
CHAT_GROUP_ID = Varchat(some kind of UUID)
MESSAGE = String

我想要实现的是:

我为这难以置信的事情苦苦挣扎!我该怎么做?

假设至少 MySql 8:

SELECT  ct.Chat_Group_ID, ct.Message, 
    ( SELECT SUM(Case when read = 1 then 0 else 1 end) 
      FROM Chats ct2
      WHERE ct2.Chat_Group_ID = ct.Chat_Group_ID
    ) as Unread
FROM (
    SELECT Chat_Group_ID, Message
       , row_number() over (partition by Chat_Group_ID order by create_at desc) rn
    FROM Chats
) ct 
WHERE ct.rn = 1

如果您需要在 MySQL v5.* 中完成,您可以使用以下查询:

SELECT tab.ID,
       tab.CHAT_GROUP_ID,
       tab.MESSAGE,
       aggregated.SUM_READ_,
       aggregated.MAX_TIME
FROM       tab 
INNER JOIN (SELECT CHAT_GROUP_ID,
                   SUM(IF(READ_=0,1,0)) AS SUM_READ_,
                   MAX(CREATED_AT)      AS MAX_TIME
            FROM tab
            GROUP BY CHAT_GROUP_ID             ) aggregated
        ON tab.CHAT_GROUP_ID = aggregated.CHAT_GROUP_ID
       AND tab.CREATED_AT = aggregated.MAX_TIME

首先,您创建一个视图,其中包含 READCREATED_AT 相对于 CHAT_GROUP_ID 的聚合值,然后使用这些信息从主 table 检索所需的信息].

试试看 here.