我在ORDER BY
子句中放置的内容并不重要,结果集的顺序不会改变。
WITH Results AS (
SELECT DISTINCT
MessageThreadUsers.threadFK,
MessageThreads.threadDate,
Messages.MessageBody,
Messages.senderFK,
Users.userFullName AS senderFullName,
ROW_NUMBER() OVER (ORDER BY MessageThreads.threadDate DESC) AS RowNumber
FROM MessageThreadUsers
JOIN MessageThreads ON MessageThreadUsers.threadFK = MessageThreads.threadID
JOIN Messages ON MessageThreads.threadDate = Messages.messageDate
JOIN Users ON Messages.senderFK = Users.userID
WHERE userFK = 'usr_developer'
)
SELECT * FROM Results WHERE RowNumber BETWEEN 1 AND 10
答案 0 :(得分:7)
ORDER BY仅在将应用于最外层SELECT语句时控制返回行的顺序。
这可能会更好:
WITH Results AS (
SELECT DISTINCT
MessageThreadUsers.threadFK,
MessageThreads.threadDate,
Messages.MessageBody,
Messages.senderFK,
Users.userFullName AS senderFullName,
ROW_NUMBER() OVER (ORDER BY MessageThreads.threadDate DESC) AS RowNumber
FROM MessageThreadUsers
JOIN MessageThreads ON MessageThreadUsers.threadFK = MessageThreads.threadID
JOIN Messages ON MessageThreads.threadDate = Messages.messageDate
JOIN Users ON Messages.senderFK = Users.userID
WHERE userFK = 'usr_developer'
)
SELECT * FROM Results WHERE RowNumber BETWEEN 1 AND 10
ORDER BY RowNumber