我有一个包含以下字段的消息表
id integer auto-incrementing field
createdate datetime
msg_to integer
msg_from integer
msg
msg_to和msg_from存储用户ID。我怎么写一个SQL查询来检索我的所有记录(msg_to = 1),因为我发了一条消息(msg_from = 1)?目标是检索所有新的消息记录。这在SQL中是可行的还是我需要在PHP中执行逻辑?
答案 0 :(得分:3)
select a.*
from `table` a
inner join (
/* last message to them */
select msg_to, max(createdate) as lastsent
from `table`
where msg_from = @MyID
group by msg_to
) b on a.msg_from = b.msg_to and a.createdate > b.lastsent
where a.msg_to = @MyID