SQL Query返回最后的消息

时间:2013-05-02 05:04:23

标签: sql

示例:

Msg

我希望你理解。 我正在尝试使用此查询,但它只返回用户1发送的查询。我还需要发送给他的那些查询。但不重复相同的参与者。

5 个答案:

答案 0 :(得分:1)

SELECT idMsg(Max), idFrom, idTo
FROM Messages
WHERE idFrom = 1 OR idTo = 1
GROUP BY idFrom
ORDER BY visualized DESC

SELECT top 1 idMsg, idFrom, idTo
FROM Messages
WHERE idFrom = 1 OR idTo = 1
ORDER BY DESC

答案 1 :(得分:0)

尝试:

SELECT idMsg, idFrom, idTo
FROM Messages
WHERE idFrom = 1 OR idTo = 1
GROUP BY idFrom
ORDER BY visualized DESC

答案 2 :(得分:0)

我会尝试像

这样的东西
SELECT MAX(id), idto, idfrom
FROM messages
WHERE idto = 1 OR idfrom = 1
GROUP BY idto, idfrom

它可能比你需要的多一点,但它很好而且清晰。

答案 3 :(得分:0)

尝试:

select case when idfrom < idto then idfrom else idto end userid1,
       case when idfrom > idto then idfrom else idto end userid2,
       max(id) id
from messages
where 1 in (idfrom, idto)
group by
       case when idfrom < idto then idfrom else idto end,
       case when idfrom > idto then idfrom else idto end

答案 4 :(得分:0)

查询:

SELECT m1.idMsg, m1.idFrom, m1.idTo
FROM Messages m1
WHERE m1.dataMsg = (SELECT MAX(m2.dataMsg)
                    FROM Messages m2
                    WHERE m2.idFrom = m1.idFrom
                    AND m2.idTo = m1.idTo)