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条回答
【Aperson】
2楼-- · 2019-01-18 11:15

add GROUP BY name to your SQL Statment - this will only bring back one of each entry from the name column

查看更多
Fickle 薄情
3楼-- · 2019-01-18 11:20

$sql="SELECT DISTINCT name FROM status =1 GROUP BY name ORDER BY name";

$query = mysqli_query($conn,$sql);
<?php while ( $fire=mysqli_fetch_array($query)) { ?>
<h4><?php echo $query['name']; ?><br></h4>
<?php } ?>
查看更多
女痞
4楼-- · 2019-01-18 11:22

Change

SELECT name FROM info WHERE status = 1 ORDER BY id

to

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

Observe that GROUP BY was added. More about group by http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

Edit:
for name with number of apparences try

SELECT name, count(name) FROM info WHERE status = 1 GROUP BY name ORDER BY id
查看更多
爷、活的狠高调
5楼-- · 2019-01-18 11:23

It's pretty simple:

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

The SQL keyword DISTINCT does the trick.

查看更多
一夜七次
6楼-- · 2019-01-18 11:24

This works for me, returns the table names for a given database.

my $sql="select distinct table_name from COLUMNS  where table_schema='$database'"
my $sth = $dbht->prepare( $sql )
      or die "Cannot prepare SQL statement: $DBI::errstr\n";
  $sth->execute
      or die "Cannot execute SQL statement: $DBI::errstr\n";

  if ($DBI::err){

    $msg= "Data fetching terminated early by error: $DBI::errstr";

}


while (@col=$sth->fetchrow_array()){
    $table[$i]=$col[0];
    $i++;
}       
查看更多
Fickle 薄情
7楼-- · 2019-01-18 11:25

use GROUP BY name statement

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

while ($raw = mysql_fetch_array($query)) {
                $name = $raw["name"];
                echo ''.$name.'<br>';
                }
查看更多
登录 后发表回答