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?
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.
Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With