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

时间:2018-12-24 14:52:31

标签: mysql sql

我有一张下一张桌子:

|--------|-----------|-------------|-------------|----------------|
| 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

2 个答案:

答案 0 :(得分:-1)

首先,我建议在数据库上使用规范化的日期格式(读取Date Types),如果要以其他格式显示,请在查询中进行转换。现在,对于您的特殊情况以及您在表上使用的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>;

您可以在此处查看一些数据的在线示例:

DB-Fiddle

答案 1 :(得分:-1)

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