艰难的SQL查询 - 自从我上次向他们发送消息以来的记录

时间:2015-04-13 03:16:16

标签: mysql sql

我有一个包含以下字段的消息表

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中执行逻辑?

1 个答案:

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