Wetts's blog

Stay Hungry, Stay Foolish.

0%

MySQL-语法-What's faster, SELECT DISTINCT or GROUP BY

转自:http://stackoverflow.com/questions/581521/whats-faster-select-distinct-or-group-by-in-mysql

They are essentially equivalent to each other (in fact this is how some databases implement DISTINCT under the hood).

If one of them is faster, it’s going to be DISTINCT. This is because, although the two are the same, a query optimizer would have to catch the fact that your GROUP BY is not taking advantage of any group members, just their keys. DISTINCT makes this explicit, so you can get away with a slightly dumber optimizer.

When in doubt, test!


If you have an index on profession, these two are synonyms.

If you don’t, then use DISTINCT.

GROUP BY in MySQL sorts results. You can even do:

1
SELECT u.profession FROM users u GROUP BY u.profession DESC

and get your professions sorted in DESC order.

DISTINCT creates a temporary table and uses it for storing duplicates. GROUP BY does the same, but sortes the distinct results afterwards.

So

1
SELECT DISTINCT u.profession FROM users u

is faster, if you don’t have an index on profession.