Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select one row without duplicate entries

In mysql table info i have :

Id , Name , City , date , status

I want to select all names from "info" Making the query

$query = mysql_query("SELECT name FROM info WHERE status = 1 ORDER BY id") 
         or die(mysql_error());

while ($raw = mysql_fetch_array($query)) 
{
  $name = $raw["name"];
  echo ''.$name.'<br>';
}

Well, the result is that it returns all the entries. I want to echo all the entries without duplicates.

Saying: under raw "name" we have inserted the name "John" 10 times.
I want to echo only one time. Is this possible?

like image 315
Darius Avatar asked Aug 12 '11 13:08

Darius


People also ask

How do I select rows without duplicates 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.

How do I select without duplicates?

SELECT DISTINCT returns only unique values (without duplicates). DISTINCT operates on a single column. DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.

How do I avoid duplicates in select query?

The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.


2 Answers

It's pretty simple:

SELECT DISTINCT name FROM info WHERE status = 1 ORDER BY id

The SQL keyword DISTINCT does the trick.

like image 87
Bohemian Avatar answered Oct 04 '22 22:10

Bohemian


try using this as your query:

SELECT DISTINCT name FROM info WHERE status = 1 ORDER BY id

to get distinct names

or as other suggested use GROUP BY

SELECT name FROM info WHERE status = 1 GROUP BY name ORDER BY id

I think the first one is more intuitive and there are no big performance difference between the two

EDIT

as the OP wants also the number of names here we go:

SELECT name,COUNT(id) AS n_names
FROM info WHERE status = 1
GROUP BY name
ORDER BY name

you can ORDER BY name or n_names depending on what you need

like image 41
Dalen Avatar answered Oct 04 '22 21:10

Dalen