Select one row without duplicate entries

2019-01-18 10:27发布

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?

8条回答
欢心
2楼-- · 2019-01-18 11:29

Let us say that you are sending bulk sms and you don't want to send the same message two times to the same guy John . What i discovered , is that using the trick of GROUP BY and ORDER BY at the same time works perfectly . But I don't say that its the best way . Here is how u can use it

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

EDIT: This is important to note, when you need more then single column and there values are unique per row then the DISTINCT was not helping.

查看更多
甜甜的少女心
3楼-- · 2019-01-18 11:32

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

查看更多
登录 后发表回答