Question

I need to distinct the left table rows on a left join.

Instead of this

|  name  |  last name  |  phone  |
|--------|-------------|---------|
|  name1 |  lastname1  | 1234567 |
|--------|-------------|---------|
|  name1 |  lastname1  | 2345678 |
|--------|-------------|---------|
|  name2 |  lastname2  | 3456789 |

I need this

|  name  |  last name  |  phone  |
|--------|-------------|---------|
|  name1 |  lastname1  | 1234567 |
|        |             | 2345678 |
|--------|-------------|---------|
|  name2 |  lastname2  | 3456789 |

I tried with a SELECT DISTINCT but without success... I tried also a GROUP BY but it hides the second row

Was it helpful?

Solution

Mariano, followed you here from your WP post that got closed.

<?php
$results = your_sql_query_here();
$data = array();

foreach( $results as $result ) {
    // Make a new array node for each name
    if ( ! isset( $data[$result['name']] )
        $data[$result['name']] = array();

    $data[$result['name']][] = $result['phone'];
}

This will give you something like this

Array(
    ['name1'] => Array(
        [0] => 5123451,
        [1] => 5123452
    ),
    ['name2'] => Array(
        [0] => 5123453,
        [1] => 5123454
    ) )

You can then just do a for loop of your $data array, using the key as your name1 value.

Or store entire data sets

<?php
$results = your_sql_query_here();
$data = array();

foreach( $results as $result ) {
    // Make a new array node for each name
    if ( ! isset( $data[$result['name']] )
        $data[$result['name']] = array();

    $data[$result['name']][] = $result;
}

Now you will have access to all nodes, but grouped by name.

Array(
    ['name1'] => Array(
        [0] => Array( 'name' => 'name1', 'phone' => 4165123, 'another_field' => 1 ),
        [1] => Array( 'name' => 'name1', 'phone' => 4165157, 'another_field' => 0 ),
        [1] => Array( 'name' => 'name1', 'phone' => 4225157, 'another_field' => 0 )
    ),
    ['name2'] => Array(
        [0] => Array( 'name' => 'name2', 'phone' => 4165123, 'another_field' => 1 ),
        [1] => Array( 'name' => 'name2', 'phone' => 4572321, 'another_field' => 1 ),
        [1] => Array( 'name' => 'name2', 'phone' => 5235157, 'another_field' => 0 )
    ) )

OTHER TIPS

You need GROUP_CONCAT:

This function returns a string result with the concatenated non-NULL values from a group.

So, your code will be:

  SELECT name, 
         last_name, 
         GROUP_CONCAT(phone) AS phones
    FROM table1
GROUP BY name, last_name;

Use GROUP_CONCAT() but beware of that fact it has the limit on character length of 1024 default,but can can be increased

SELECT name, 
last_name, 
GROUP_CONCAT(DISTINCT phone SEPARATOR ' ')
FROM table1 
GROUP BY name, last_name

See fiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top