Select UNIQUE or DISTINCT MySQL/PHP Queries

Bookmark and Share

How to filter / remove duplicate items in your database query result using DISTINCT

Say you wanted to show a list of client names from using a portfolio projects database. The problem is you may have multiple portfolio projects for the same client. So if you ran that list, you could get something like: Nike, Nike, Audi, BMW, BMW, Kmart and Ford. Here is how to clean up all duplicate using the “DISTINCT” clause.

$query = "SELECT DISTINCT Client_Name FROM Portfolio ORDER BY Client_Name ASC";
$result = query_db($query);
 
while ($myrow = mysql_fetch_array($result))
{
echo $myrow[Client_Name].", ";
}

Notice how we did not add in “limit 0,1″. DISTINCT does this for us. It will only return one item.

You want to use it without any other columns, otherwise you are going to need a GROUP BY clause.

Please rate this post by clicking a star:

(6 votes, average: 4.00 out of 5)

Leave a Reply





Tags: , , , , , , ,