问题
Consider the two tables below:
user:
ID | name
---+--------
1 | Alice
2 | Bob
3 | Charlie
event:
order | user
------+------------
1 | 1 (Alice)
2 | 2 (Bob)
3 | 3 (Charlie)
4 | 3 (Charlie)
5 | 2 (Bob)
6 | 1 (Alice)
If I run the following query:
SELECT DISTINCT user FROM event ORDER BY "order" DESC;
will it be guaranteed that I get the results in the following order?
1 (Alice)
2 (Bob)
3 (Charlie)
If the three last rows of event
are selected, I know this is the order I get, because it would be ordering 4, 5, 6 in descending order. But if the first three rows are selected, and then DISTINCT
prevents the last tree to be loaded for consideration, I would get it in reversed order.
Is this behavior well defined in SQL? Which of the two will happen? What about in SQLite?
回答1:
No, it will not be guaranteed.
Find Itzik Ben-Gan's Logical Query Processing Phases poster for MS SQL. It migrates over many sites, currently found at https://accessexperts.com/wp-content/uploads/2015/07/Logical-Query-Processing-Poster.pdf .
DISTINCT
preceeds ORDER BY .. TOP
and Sql Server is free to return any of 1 | 1 (Alice)
or 6 | 1 (Alice)
rows for Alice. So any of (1,2,3), (1,4,5) an so on are valid results of DISTINCT
.
回答2:
Here's a query solution that I believe solves your problem.
SELECT
MAX([order]) AS MaxOrd
, [user]
FROM Event
GROUP BY [User]
ORDER BY MaxOrd DESC
来源:https://stackoverflow.com/questions/37257746/how-does-distinct-interact-with-order-by