Eliminating Duplicates from a Query Result
Problem
You want to select rows in a query result in such a way that it contains no duplicates.
Solution
Use SELECT DISTINCT.
Discussion
Rows in query results sometimes
contain duplicate rows. This is particularly common when you select
only a subset of the columns in a table, because that reduces the
amount of information available that might otherwise distinguish one
row from another. To obtain only the unique rows in a result,
eliminate the duplicates by adding the DISTINCT
keyword. That tells MySQL to return only one instance of each set of
column values. For example, if you select the name columns from the
cat_mailing table without using
DISTINCT, several duplicates occur:
mysql>SELECT last_name, first_name->FROM cat_mailing ORDER BY last_name, first_name;+-----------+-------------+ | last_name | first_name | +-----------+-------------+ | Baxter | Wallace | | BAXTER | WALLACE | | Baxter | Wallace | | Brown | Bartholomew | | Isaacson | Jim | | McTavish | Taylor | | Pinter | Marlene | | Pinter | Marlene | +-----------+-------------+
With DISTINCT, the duplicates are eliminated:
mysql>SELECT DISTINCT last_name, first_name->FROM cat_mailing ORDER BY last_name;+-----------+-------------+ | last_name | first_name | +-----------+-------------+ | Baxter | Wallace | | Brown | Bartholomew | | Isaacson | Jim | | McTavish | Taylor | | Pinter | Marlene | +-----------+-------------+
An alternative to DISTINCT is to add a
GROUP BY clause that names ...