我的SQL非常生疏,我想确保我不会在任何类型的负载下编写失败的东西。
我有一个Message表,如下所示:
ID int [PK]
ThreadId nvarchar(32)
Read bit
Archived bit
Timestamp datetime
/*---Other non-relevant columns---*/
Sender_MemberId int [FK]
Receiver_MemberId int [FK]
与Gmail类似,我希望能够根据正常的消息使用情况(收件箱,已发送,存档等)提取该线程的所有线程和所有消息。
这是我目前用于收件箱的SQL:
SELECT * FROM [Messages]
WHERE [ThreadId] IN
(
SELECT [ThreadId]
FROM [Messages]
WHERE ([Receiver_MemberId] = @MemberId)
)
ORDER BY [ThreadId] DESC, [Timestamp] DESC
这可以按我的意愿运作,但是有更好的方法吗?或者如果没有,我应该拥有什么索引?
更新:根据Aaron的好建议,我已经添加了分页功能,并减少了我正在接下来的信息量。
新SQL:
SELECT DISTINCT m.[ThreadId], m.[Subject], m.[To], m.[From], m.[Timestamp]
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY MessageId) AS RowNumber , ThreadId
FROM [Messages]
WHERE [Sender_MemberId] = @p1
)
AS t
INNER JOIN [Messages] m ON m.ThreadId = t.ThreadId
WHERE t.RowNumber BETWEEN @Skip + 1 AND @Skip + @Take
ORDER BY [Timestamp] DESC
答案 0 :(得分:1)
您不需要子查询,这应该
SELECT Id
, [ThreadId]
, read
, archived
, timestamp
FROM [Messages]
WHERE [Receiver_MemberId] = @MemberId
ORDER BY [ThreadId] DESC, [Timestamp] DESC
最好为您需要的列命名,而不是使用*