MySQL查询选择DISTINCT但显示所有行

时间:2013-01-22 09:43:09

标签: php mysql select

我需要DISTINCT的帮助。我想显示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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分: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,不要在生产中使用它们。

答案 1 :(得分: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; 
    }
}