SQL组两列,然后选择最近的日期/时间戳

时间:2020-11-08 05:54:30

标签: mysql sql

因此,我有一个名为phone_messages的表。这是我编写的示例查询。我想要做的是将具有character_id 22或target_character_id 22的行组合在一起。因为在数据库中存储的每个phone_message中,这是两个条目。基本上是电话交谈。我想做的是在每个组中分组获取最后发送的消息。

我的原始查询:

SET @character_id = 22;
SET @t = 'text';

SELECT character_id, target_character_id, message, `type`, MAX(`date`) date FROM
    `phone_messages`
WHERE
    (
        `character_id`=@character_id
    ) AND `type`=@t
GROUP BY
    character_id, target_character_id

character_id | target_character_id | message | type | date
"22"    "33"    "correct"   "text"  "2020-08-25 23:28:31"
"33"    "22"    "perfect see you then"  "text"  "2020-08-25 23:28:43"
"57"    "22"    "where is this mega mall" "text" "2020-09-05 19:05:25"
"22"    "57"    "the tool shop down south"  "text"  "2020-09-05 19:05:45"

我想要的输出是

character_id | target_character_id | message | type | date
"33"    "22"    "perfect see you then"  "text"  "2020-08-25 23:28:43"
"22"    "57"    "the tool shop down south"  "text"  "2020-09-05 19:05:45"

我将如何去做?对不起,我的问题没有得到理解。

2 个答案:

答案 0 :(得分:1)

只需确认

  • 对于每个“一对”呼叫者(其中一个是“ 22”)
  • 您想获取最新的文本(从22开始或从22开始)

这里的答案使用以下方法

  • 对于每一行,确定另一方(在查询中称为second_character_id
  • 对于对方,请根据发送日期对“文本”行进行排序
  • 获取各方的最新行
WITH Call_list AS
    (SELECT *,
        @character_id AS `primary_character_id`,
        CASE 
            WHEN `character_id` = @character_id THEN `target_character_id`
            ELSE `character_id` END AS `second_character_id`
    FROM
        `phone_messages`
    WHERE
        (`character_id`= @character_id OR `target_character_id`= @character_id)
        AND (`type`= @t )
    ),
Sorted_Call_List AS
    (SELECT *,
            ROW_NUMBER() OVER 
                (PARTITION BY `primary_character_id`, `second_character_id` 
                ORDER BY `Date` DESC
                ) AS char_rn
    FROM Call_list
    )
SELECT `character_id`, `target_character_id`, `message`, `type`, `date`
FROM   Sorted_Call_List
WHERE  char_rn = 1;

在此答案中,我还包括了primary_character_id(在这种情况下始终为22),以防您想将其扩展为可容纳多人。

这里是db<>fiddle,其中包含数据设置和方法。

请注意,在底部还有一个附加查询-这是我以前的尝试,我对需求有误解。在该答案中,它查找到/来自22的最新“传入”和最新的“传出”文本,而不管它们来自谁。

答案 1 :(得分:0)

如果您希望每对都获得最新消息,而不考虑顺序,则可以将ROW_NUMBER()LEAST()GREATEST()结合使用:

SET @character_id = 22;
SET @t = 'text';

SELECT pm.*
FROM (SELECT pm.*,
           ROW_NUMBER() OVER (PARTITION BY LEAST(character_id, target_character_id), GREATEST(character_id, target_character_id)
                              ORDER BY date DESC
                             ) as seqnum
      FROM phone_messages pm
      WHERE character_id = @character_id AND
            type = @t
     ) pm
WHERE seqnum = 1;