Group SQL query results by a field

1

I have a table like this:

|  ID  |  id_foreign  | cosa  |
-------------------------------
|  1   |      1       | cosa1 |
|  2   |      1       | cosa2 |
|  3   |      2       | cosa1 |
|  4   |      3       | cosa1 |
|  5   |      4       | cosa1 |
|  6   |      4       | cosa2 |
|  7   |      4       | cosa3 |
|  8   |      4       | cosa4 |
-------------------------------

What I want is Show with php and html a table where I get, for example:

|   id_foreign  |   cosas    |
------------------------------
|      1        |   · cosa1  |
|               |   · cosa2  |
------------------------------
|      2        |   · cosa1  |
------------------------------
|      3        |   · cosa1  |
------------------------------
|      4        |   · cosa1  |
|               |   · cosa2  |
|               |   · cosa3  |
|               |   · cosa4  |
------------------------------

How should the consulate do to obtain that result?

Or rather it has to be done with sql or can it be done with php?

Thanks

    
asked by Pavlo B. 10.02.2017 в 12:44
source

3 answers

1

try this:

SELECT id_foreign,group_concat(concat(' . ',cosa) separator '<br>') as cosas    
from table
group by id_foreign
    
answered by 10.02.2017 / 12:52
source
1

I do not know if you use PDO , mysqli , etc, so I'll do it in a separate code:

<?php
/* Simulo una variable con tu contenido para obtener registros de ella
  basta con un SELECT * FROM tabla , no hay necesidad de usar GROUP BY */
$registros = [
  [ 'ID' => 1, 'id_foreign' => 1, 'cosa' => 'cosa1' ],
  [ 'ID' => 2, 'id_foreign' => 1, 'cosa' => 'cosa2' ],
  [ 'ID' => 3, 'id_foreign' => 2, 'cosa' => 'cosa1' ],
  [ 'ID' => 4, 'id_foreign' => 3, 'cosa' => 'cosa1' ],
  [ 'ID' => 5, 'id_foreign' => 4, 'cosa' => 'cosa1' ],
  [ 'ID' => 6, 'id_foreign' => 4, 'cosa' => 'cosa2' ],
  [ 'ID' => 7, 'id_foreign' => 4, 'cosa' => 'cosa3' ],
  [ 'ID' => 8, 'id_foreign' => 4, 'cosa' => 'cosa4' ],
];

$datos = [];
/* Creamos una matriz con índice 'id_foreign' con elementos variables */
foreach ($registros as $registro) {
  $datos[$registro['id_foreign']][] = $registro;
}
?><table border="1">
<tr><th>id_foreign</th><th>cosa</th></tr>
<?php
/* Obtenemos una a una cada una de las id_foreign */
foreach ($datos as $id_foreign => $fila) {
  /* Ahora, por cada elemento que tenga cada id_foreign creamos una fila */
  foreach ($fila as $indice => $elemento) {
?>  <tr>
<?php
    /* Si es el primer elemento deberemos crear la celda que muestra el id_foreign y decirle el alto (la cantidad de elementos que contiene) */
    if ($indice === 0) {
?>    <td rowspan="<?= count($fila) ?>"><?= htmlentities($id_foreign) ?></td>
<?php
    }
?>    <td><?= htmlentities($elemento['cosa']) ?></td>
  </tr>
<?php
  }
} 
?>
</table>
    
answered by 10.02.2017 в 13:27
-1

If you need to group fields, I think you should look at the GROUP BY clause Example link

    
answered by 10.02.2017 в 12:49