dido
dido

Reputation: 2361

How to show duplicate records in MySQL and combine records with PHP?

I have a table with following structure:

TBL1

COL1 COL2 COL2
---- ---- ----
A    B    1
B    C    3
A    C    11
A    D    13

SELECT TBL1.COL1, COL2 FROM TBL1
INNER JOIN (SELECT COL1, count(COL1) as CNT FROM TBL1
GROUP BY COL1 HAVING CNT > 1) dup ON TBL1.COL1= dup.COL1 ORDER BY COL1;

This query returnug this:

COL1 COL2 COL2
---- ---- ----
A    B    1
A    C    11
A    D    13

I want to combine match records. If you have not understood me, the result that I want to show is:

------------------------
RESULT
------------------------

A -> B 1
     C 11
     D 13

Ie for A has the following values ​​B 1, C 11 and D 13

If I using FOREACH the result is :

------------------------
RESULT
------------------------

A -> B 1
A -> C 11
A -> D 13

Thanks in advance !

Upvotes: 1

Views: 370

Answers (1)

Martin
Martin

Reputation: 6015

You should track the current value of COL1 in your foreach, like this:

$col1 = null;
foreach(mysql_fetch_assoc($res) as $row) {
    if(is_null($col1) || $row['COL1'] != $col1) {
        echo $row['COL1'] . " -> ";
        $col1 = $row['COL1'];
    } else {
        echo "    ";
    }

    echo $row['COL2'] . " " . $row['COL3'] . "\n";
}

Upvotes: 2

Related Questions