Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql distinct row or distinct field

Tags:

mysql

distinct

Is there a performance or other difference between this:

SELECT distinct(users.id),2 as someFieldName ,0 as someOtherFieldName
From users join ...

and this:

SELECT distinct users.id ,2 as someFieldName ,0 as someOtherFieldName
From users join ...

result set is used as part of an insert statement and the select might return the same user i.d multiple time due to the join (not displayed here)

I am using mysql.

like image 740
epeleg Avatar asked Oct 24 '12 08:10

epeleg


Video Answer


2 Answers

There is no difference as DISTINCT in this context only operates on rows.

From the SELECT docs

The ALL and DISTINCT options specify whether duplicate rows should be returned. ALL (the default) specifies that all matching rows should be returned, including duplicates. DISTINCT specifies removal of duplicate rows from the result set. It is an error to specify both options. DISTINCTROW is a synonym for DISTINCT.

like image 33
davek Avatar answered Sep 21 '22 21:09

davek


There is no such thing as "distinct field". Your first syntax is parsed identically to the second: the parentheses merely surround a field expression. You could also write:

SELECT DISTINCT (users.id), (2) AS someFieldName, (0) AS someOtherFieldName

They are all equivalent.

If you want to avoid comparisons on your constant columns, you could instead use GROUP BY:

SELECT   users.id, 2 AS someFieldName, 0 AS someOtherFieldName
FROM     users JOIN ...
GROUP BY users.id
like image 65
eggyal Avatar answered Sep 20 '22 21:09

eggyal