仅从数据库mysql获取最后的消息

zmeyuzjn  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(283)

我有一张和下一张一样的table:

|--------|-----------|-------------|-------------|----------------|
| id     | userToId  | userFromId  | message     |   date         |
|--------|-----------|-------------|-------------|----------------|
|  1     |   1       |   2         |  Hi         |06/30/2018/18:00|
|--------|-----------|-------------|-------------|----------------|
|  2     |   1       |   2         |  how r u    |06/30/2018/18:01|
|--------|-----------|-------------|-------------|----------------|
|  3     |   3       |   5         |  Hi         |06/30/2018/17:00|
|--------|-----------|-------------|-------------|----------------|
|  4     |   1       |   5         |  Hi         |06/30/2018/19:00|
|--------|-----------|-------------|-------------|----------------|
|  5     |   7       |   1         |  Hi         |06/30/2018/19:00|
|--------|-----------|-------------|-------------|----------------|

而且,我只想获取与特定用户提供的信息相关的最后消息(发送或接收) user ID . 例如,如果 user ID1 那么输出应该如下所示:

|--------|-----------|-------------|-------------|----------------|
| id     | userToId  | userFromId  | message     |   date         |
|--------|-----------|-------------|-------------|----------------|
|  2     |   1       |   2         |  how r u    |06/30/2018/18:01|
|--------|-----------|-------------|-------------|----------------|
|  4     |   1       |   5         |  Hi         |06/30/2018/19:00|
|--------|-----------|-------------|-------------|----------------|
|  5     |   7       |   1         |  Hi         |06/30/2018/19:00|
|--------|-----------|-------------|-------------|----------------|

此输出意味着(对于具有 id = 1 )从其他用户收到的最新消息是:

"how r u" -> from user with id = 2
"Hi" -> from user with id = 5

发送给其他用户的最新消息是:

"Hi" -> to user with id = 7
bxgwgixi

bxgwgixi1#

首先,我建议对数据库使用规范化的日期格式(读取日期类型),如果希望以其他格式显示,则在查询中转换它。现在,针对你的特殊情况 datetime 您在表上使用的格式,我将继续下一个查询:

SELECT
    m.*
FROM
    msgs AS m
INNER JOIN
    ( SELECT
          userToId,
          userFromId,
          MAX(STR_TO_DATE(`date`, '%m/%d/%Y/%H:%i')) AS maxDate
      FROM
          msgs
      GROUP BY
          userToId, userFromId
     ) AS l ON l.userToId = m.userToId
            AND l.userFromId = m.userFromId
            AND l.maxDate = STR_TO_DATE(m.`date`, '%m/%d/%Y/%H:%i')
WHERE
    m.userToId = <your_user_id> OR m.userFromId = <your_user_id>;

您可以通过以下数据查看在线示例:
小提琴

nmpmafwu

nmpmafwu2#

https://www.db-fiddle.com/f/wlehj1egnt9zjecyzenccb/0

SELECT t.*
FROM my_table t
LEFT JOIN my_table temp
ON t.userToId = temp.userToId
   AND t.userFromId = temp.userFromId
   AND t.date < temp.date
WHERE (t.userToId = 1
       OR t.userFromId = 1)
       AND temp.id IS NULL

相关问题