Mysql and PHP grouping

Asked

Viewed 100 times

3

I need to group a query with a detail, the grouping should be done only when the information is repeated in sequence, for example:

id     nome
1      lucas
2      lucas
3      marcos
4      lucas
5      marcos

In the example above, only the "Bowls" with ID’s 1 and 2 can be grouped, the other information is not, because they are not in sequence.

Follows excerpt from the query:

$SQL = "select * from clientes where id = '".$id."' group by nome order by id desc ";
$RSS = mysql_query($SQL, $conexao);
while($RS = mysql_fetch_array($RSS)){
  echo $RS["nome"]."<br>";
}

1 answer

2


Instead of using SQL’s GROUP BY, let’s merge the names in sequence in the PHP code.

Would look like this:

$SQL = "SELECT * FROM clientes ORDER BY id";
$RSS = mysql_query($SQL, $conexao);
while($RS = mysql_fetch_array($RSS)){
  if ($RS["nome"] != $nome_atual)
    echo $RS["nome"]."<br>";
  $nome_atual = $RS["nome"];
}

Without the Mysql 'GROUP BY' clause, the names will come in the informed sequence. if checks if the name received from the bank is different from the previous one. If so, it publishes.

  • I don’t think that’s the affirmative if' verifica se o nome recebido do banco é diferente do anterior. Se for, ele publica be correct. First, the query will return ONE AND ONLY ONE RECORD, record that whose id is equal to the $id variable and will print on the screen the name corresponding to that id because there will be no previous name to compare. So your answer was accepted with 2 ups not know why!!

  • You’re right, @Leocaracciolo. I was just worried about the PHP code of not repeating the name. In SQL I only took GROUP BY. Now the query brings all the records and in ascending order, according to the question. I thank you for the comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.