简体   繁体   English

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

[英]MySQL query select DISTINCT but display all rows

I need help with DISTINCT . 我需要DISTINCT帮助。 I would like to display Distinct row but display also all rows 我想显示不同的行,但还要显示所有行

Example this table from database: 此表来自数据库的示例:

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

I would like the display to look like this : 我希望显示器看起来像这样:

A
one  |two
three|four
five |six

B
seven|eight
nine |ten

Can anyone help? 有人可以帮忙吗?

The easiest way would be to fetch all rows from the database, and then group them in PHP. 最简单的方法是从数据库中获取所有行,然后在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 />";
    }
}

Yields: 产量:

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

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

Note that I use the deprecated mysql_functions just for simplicity, do not use them in production. 请注意,为简单起见,我使用了不推荐使用的mysql_functions,请勿在生产中使用它们。

Here is how you can do it 这是你怎么做

$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);

This will fetch this output 这将获取此输出

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; 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM