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

最简单的方法是从数据库中获取所有行,然后在 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 回答
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 回答