Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Ignore a selected column when using DISTINCT

Tags:

mysql

distinct

Let's say:

  1. I want to query colA, colB and colC in my table.

  2. I want to see DISTINCT values but I don't want colA to be a criteria for distinction.

  3. Omitting colA isn't an option.

What's the best way to structure that query?

like image 688
JLeonard Avatar asked May 26 '10 23:05

JLeonard


People also ask

How do I get distinct to only one column?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.

Does SELECT distinct apply to all columns?

Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.

Do you need a GROUP BY when using distinct?

Well, GROUP BY and DISTINCT have their own use. GROUP BY cannot replace DISTINCT in some situations and DISTINCT cannot take place of GROUP BY. It is as per your choice and situation how you are optimizing both of them and choosing where to use GROUP BY and DISTINCT.

Does distinct apply to multiple columns?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.


1 Answers

There are two cases here. Let's say you have the data

A  B  C   (columns)
a  b  c1
a  b  c2

Taking distinct values of A, B gives just one result (a,b), with two values for column C. So the question is do you want to see all values of C or just one value for each distinct value of columns A and B?

If you want to see just one value of C, then you can write

SELECT A, B, MAX(C) FROM YourTable
  GROUP BY A, B

On the other hand, if you want to see all values for C then

SELECT DISTINCT A, B, C FROM YourTable WHERE ROW(A,B) IN 
  (SELECT A, B FROM YourTable
     GROUP BY A, B)

gives you that. This last alternative is needed if there are other columns in the table.

like image 118
mdma Avatar answered Oct 22 '22 07:10

mdma