mysql - SQL嵌套查询问题

标签 mysql sql

我有一个包含表 MESSAGE 的数据库,它包含我的所有消息。 我需要找到所有最后的对话消息。

该表包含以下字段: 身份证号(整数) 来自(整数) 至(整数) 日期(日期) 消息(varchar)

我需要找到一个查询,该查询可以返回所有最后的消息。 例如:

1 -> 3 : This is a first message; yesterday
3 -> 1 : This is the last one; today
1 -> 2 : Another message with 1 and 2; some time
3 -> 5 : Some message i don't need; some time

我需要找到:

"3 -> 1 : This is the last one; today"
"1 -> 2 : Another message with 1 and 2; some time"

我希望我的意思很清楚...... 我已经可以通过以下查询找到与我对话的用户:

在此示例中,用户的 Id = 47

select distinct m.To from MESSAGE m Where m.From = 47 union select distinct m2.from From MESSAGE m2 where m2.To = 47

谢谢!

最佳答案

我认为这会做你想要的,假设 id 可以用来定义“最后一条消息”:

select m.*
from message m join
     (select least(from, to) as p1, greatest(from, to) as p2, max(id) as maxid
      from message m
      group by least(from, to), greatest(from, to)
     ) mmax
     on m.id = mmax.maxid

这使用 id 来查找对话中的最后一条记录。然后它会返回以获取消息。

关于mysql - SQL嵌套查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748256/

相关文章:

mysql - SQL 分页尝试 : OFFSET (offset) is not a valid input at this position

mysql - MySQL显示rownum问题

mysql - INNER JOIN、LEFT JOIN、RIGHT JOIN 和 FULL JOIN 有什么区别?

mysql - 检查表中是否存在数据,然后在单独的表中进行比较

PHP PDO 获取不工作?

mysql - XML 导入到 WordPress 数据库

php - 使用准备好的语句 PHP 返回 MySQL 错误代码和自定义响应

php - SQL中如何将数据从一行复制到另一行

计数不同时的 MySQL 案例

php - "Your PHP installation appears to be missing the MySQL extension which is required by WordPress."