Select Distinct without sorting
I used a Select Distinct query, which resulted me a sorted data. Is there 开发者_JS百科anyway that i dont get data sorted?
I'll try to elaborate a bit as to what's going on and why... though I agree with @vic's comment to the question...
- Without explicitly stating an order (via an
order by
clause) there is absolutely no guarantee of any order in the result set. - Practically speaking, many queries will return a consistent order based on the query plan and how the data is actually stored and accessed... DO NOT RELY ON THIS!
- Specifically, for a
distinct
query, the sql engine will sort the data so that it can be sure to remove any duplicates.
In short, if the order of the result set matters (even if the desired order is "random") you must ALWAYS explicitly state it. That said, from a purely set-based-math/sql standpoint, the order of the result shouldn't matter.
Put this at the end of your query. This will effectively randomize the results which then will appear to you non-sorted ;)
ORDER BY Rnd([ID]);
Replace the ID
with primary key of the table. In Access SQL it is possible to call certain VB Functions directly. In this case the Rnd
function can be called in a query and fed a seed value from the data being sorted.
I think sorting may have something to do with the way DISTINCT is determined. The easiest way to return distinct values is to sort the selection set returned by processing the SQL predicate and then returning only the rows where the DISTINCT columns change value from the prior row.
In short, DISTINCT requires a sort to be performed where duplicate rows are dropped.
That said, there is no guarantee that rows are returned to you in any particular order unless you explicitly include an ORDER BY clause.
精彩评论