ORDER BY仅在应用于最外层的SELECT语句时控制返回行的顺序。
不管我在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
这可能效果更好:
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