我想得到用户最近的消息。我需要把最后的信息识别给每个人。我该怎么做呢?谢谢!
结构:

查询
SELECT *
FROM `messages`
WHERE (
`from` = 1 OR
`to` = 1
)
GROUP BY (`from` + `to`)
ORDER BY `id` DESC
LIMIT 10结果

我需要什么?

如果你有同样的问题?我找到解决办法了!
SELECT `id`, `from`, `to`, `text`, `created`
FROM (
SELECT *, (`from` + `to`) AS `anchor`
FROM `messages`
WHERE (
`from` = 1 OR
`to` = 1
)
ORDER BY `id` DESC
LIMIT 1
) AS `*`
GROUP BY `anchor`;发布于 2019-08-12 16:31:18
如果我正确理解,您可以使用关联子查询:
select m.*
from messages m
where 1 in (m.from, m.to) and
m.id = (select max(m2.id)
from messages m2
where (m2.from = m.from and m2.to = m.to) or
(m2.from = m.to and m2.to = m.from)
);注意:from和to实际上是列的坏名称,因为它们是SQL关键字。
https://stackoverflow.com/questions/57464916
复制相似问题