Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit distinct keyword to one column

Tags:

sql

mysql

how do i apply the the distinct keyword in mysql so that it is only checking that one column field is unique, while still returning other columns from my table?

like image 532
gsueagle2008 Avatar asked Apr 09 '09 04:04

gsueagle2008


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.

Can distinct command be used for more than one column?

The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a result set. The DISTINCT clause keeps one row for each group of duplicates. The DISTINCT clause can be applied to one or more columns in the select list of the SELECT statement.

How do I SELECT a record without duplicates in one column in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.


2 Answers

For being able to do that, mysql must know what to do with the other columns. You GROUP BY the column that should be unique and use a function that will tell it what to do with the others (a so-called aggregate function). MAX() and COUNT() are common examples:

SELECT studentId, COUNT(courseId) AS AmountEnrolledCourses
FROM student_enrollment
GROUP BY studentId

SELECT athlete, MAX(distance) AS PersonalRecord
FROM longjump
GROUP BY athlete
like image 166
soulmerge Avatar answered Sep 17 '22 20:09

soulmerge


You'll need to use group by instead.

SELECT SUM(A), MIN(B), C FROM TABLE WHERE A > 1 GROUP BY C;

Note that if you're grouping on one column and returning others you have to provide some sort of way to cram all those values in the other fields into one. That way is called an aggregate function, and you'll have to check the manual for your database version to know exactly what your options are. See http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html for mysql.

like image 25
easel Avatar answered Sep 18 '22 20:09

easel