How does SELECT DISTINCT work in MySQL?

I have a table with several rows that have the same data. I used SELECT DISTINCTto get a unique string, and it works great. But when I use ORDER BYwith SELECT DISTINCT, it gives me unsorted data.

Can someone tell me how different works?

Based on what criteria does he select a row?

+5
source share
3 answers

From your comment earlier, the request you are trying to run is

Select distinct id from table where id2 =12312 order by time desc.

As I expected, here is your problem. Your selection column and column order are different. The output lines are ordered by time, but this order need not be stored in the id column. Here is an example.

id  | id2    | time
-------------------
1   | 12312  | 34
2   | 12312  | 12
3   | 12312  | 48

If you run

SELECT * FROM table WHERE id2=12312 ORDER BY time DESC

id  | id2    | time
-------------------
2   | 12312  | 12
1   | 12312  | 34
3   | 12312  | 48

, ,

id
--
2
1
3

.

+2

SELECT DISTINCT, , . "duplicates" , . , , , :

 id  |  num
 --------------
 1   |  1 
 2   |  3
 3   |  3

SELECT DISTINCT * , SELECT DISTINCT num :

num
-----
1
3

, - (, 2 3), , , .

, DISTINCT , ORDER BY .

: MySQL SELECT

+1

, , , ORDER BY , SELECT. SQL , MySQL .

:

SELECT DISTINCT colum1, column2
FROM table1
WHERE ...
ORDER BY column3

, table1 :

 id | column1 | column2 | column3
----+---------+---------+---------
  1 | A       | B       | 1
  2 | A       | B       | 5
  3 | X       | Y       | 3

ORDER BY ( ORDER BY ):

 column1 | column2
---------+---------
 A       | B
 X       | Y

ORDER BY column3 .

DISTINCT , SELECT. 1 , (A, B) # 1. , # 2 , SELECT (A, B), . - DISTINCT . № 3 (X, Y), . ORDER BY column3 (A, B), (X, Y).

# 2 # 1, , , , (X, Y), (A, B).

. , .

SQL, , , .

0

All Articles