I was doing some experiments with the DISTINCT
keyword and some particular situations caught up my attention.
First of all I noticed that I can put some parenthesis with DISTINCT
, for example:
SELECT DISTINCT(NAME) FROM EMPLOYEE;
is ok, while
SELECT DISTINCT(NAME, SURNAME) FROM EMPLOYEE;
gives me an error. Why?
And what's the sense of allowing operations like this one?
SELECT DISTINCT(NAME), COUNT(SURNAME) FROM EMPLOYEE;
DISTINCT
(or DISTINCTROW
) is not a function; it is an option of the SELECT
statement that tells MySQL to strip duplicate rows from the resultset generated by the query. By default it returns all the generated rows, including the duplicates.
It can also be used together with COUNT()
aggregate function (as COUNT(DISTINCT expr)
) and it has the same meaning: it ignores the duplicates.
Because DISTINCT
is not a function, DISTINCT(NAME)
is interpreted as DISTINCT
followed by the expression (NAME)
(which is the same as NAME
).
SELECT DISTINCT(NAME, SURNAME) FROM EMPLOYEE
doesn't work because (NAME, SURNAME)
is not a valid MySQL expression.
DISTINCT
is nothing really -- more of a modifier. It is used in two places. It can modifier aggregation functions. The only one worth using is COUNT(DISTINCT)
.
In your case, you are using it as a modifier to SELECT
. It simply says that each entire row should be distinct.
So, when you say:
SELECT DISTINCT (name, surname)
This is the same as getting all distinct rows of (name, surname)
from this query:
SELECT (name, surname)
MySQL does not recognize this syntax. In some databases, this represents a tuple or row constructor. But, because MySQL does not recognize this syntax, you are getting an error.
As a note: SELECT DISTINCT
can be quite powerful but it is often not necessary. More typically, you can do a GROUP BY
with the column you actually want "distinct"ed. For instance:
SELECT name, surname, COUNT(*)
FROM t
GROUP BY name, surname
ORDER BY COUNT(*) DESC;
This query actually shows the duplicates and how often they occur.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.