CREATE TABLE Messages
(
MessageID INT
, fromUserID INT
, toUserID INT
, TimeSent DATETIME
);
INSERT INTO Messages VALUES (1, 10, 11, GetDate());
INSERT INTO Messages VALUES (2, 11, 10, GetDate());
INSERT INTO Messages VALUES (3, 11, 12, GetDate());
INSERT INTO Messages VALUES (4, 11, 10, GetDate());
INSERT INTO Messages VALUES (5, 11, 12, GetDate());
INSERT INTO Messages VALUES (6, 11, 10, GetDate());
INSERT INTO Messages VALUES (7, 11, 12, GetDate());
INSERT INTO Messages VALUES (8, 11, 12, GetDate());
INSERT INTO Messages VALUES (9, 11, 10, GetDate());
INSERT INTO Messages VALUES (10, 11, 12, GetDate());
INSERT INTO Messages VALUES (11, 11, 10, GetDate());
INSERT INTO Messages VALUES (12, 11, 12, GetDate());
DECLARE @t TABLE (MessageID INT);
DECLARE @From INT;
DECLARE @To INT;
DECLARE cur CURSOR FOR
SELECT fromUserID, toUserID
FROM Messages
GROUP BY fromUserID, toUserID;
OPEN cur;
FETCH NEXT FROM cur INTO @From, @To;
WHILE @@FETCH_STATUS=0
BEGIN
INSERT INTO @t
SELECT TOP(2) MessageID
FROM Messages
WHERE fromUserID = @From AND toUserID = @To
ORDER BY TimeSent DESC;
FETCH NEXT FROM cur INTO @From, @To;
END
CLOSE cur;
DEALLOCATE cur;
SELECT *
FROM Messages
INNER JOIN @t tt ON Messages.MessageID = tt.MessageID
这可能是一个例子:
这将为 fromUserID 和 toUserID 之间的每个对话返回 2 条最新消息。更改
TOP(2)
为TOP(20)
以获取 20 个最近的对话。我确定这不是执行此操作的最佳方法;我相信它可以以基于集合的方式完成,而不是这里显示的基于游标的程序方式。
目前还不清楚你在追求什么。所以,这个猜测可能是错误的: