0

助けが必要DISTINCTです。個別の行を表示したいが、すべての行も表示したい

データベースからのこのテーブルの例:

+----+-----+-----+
|col1|col2 |col3 |
+----+-----+-----+
|A   |one  |two  |
|A   |three|four |
|A   |five |six  |
|B   |seven|eight|
|B   |nine |ten  |
+----+-----+-----+

ディスプレイを次のようにしたいと思います:

A
one  |two
three|four
five |six

B
seven|eight
nine |ten

誰か助けてもらえますか?

4

2 に答える 2

0

これがあなたがそれをする方法です

$query="select 
            distinct    (col1) as col1,
            GROUP_CONCAT(col2) as col2,
            GROUP_CONCAT(col3) as col3
        FROM test
        group by col1";
$query = mysql_query($query);

これにより、この出力がフェッチされます

col1    col2            col3 
A       one,three,five  two,four,six 
B       seven,nine      eight,ten 

while($row = mysql_fetch_assoc($query)) 
{
    $col1 = $row['col1'];
    $col2   =   explode(',',$row['col2']);
    $col3   =   explode(',',$row['col3']);

    for($i=0;$i<=count($col2);$i++)
    {
        $value  =   '';
        if(isset($col2[$i])){
            $value  =   $col2[$i];
            $value  .=  ' | ';
        }
        if(isset($col3[$i])){
        $value  .=  $col3[$i];
        }
            echo $value; 
    }
}
于 2013-01-22T10:31:43.447 に答える
0

最も簡単な方法は、データベースからすべての行をフェッチしてから、それらをPHPでグループ化することです。

// Querying:
$query = mysql_query('select * from tbl');
$results = array(); // Store all results in an array, grouped by col1

while($row = mysql_fetch_assoc($query)) {
    $col1 = $row['col1'];

    // This is basically grouping your rows by col1
    if(!isset($results[$col1]))
        $results[$col1] = array();
    $results[$col1][] = $row;
}

// Displaying:
foreach($results as $col1 => $rows) {
    echo "<h1>" . $col1 . "</h1>";

    foreach($rows as $row) {
        echo $row['col2'] . "|" . $row['col3'] . "<br />";
    }
}

収量:

<h1>A</h1>
one  |two
three|four
five |six

<h1>B</h1>
seven|eight
nine |ten

簡単にするために非推奨のmysql_functionsを使用していることに注意してください。本番環境では使用しないでください。

于 2013-01-22T09:51:03.483 に答える