【问题标题】:MySQL query select DISTINCT but display all rowsMySQL查询选择DISTINCT但显示所有行
【发布时间】:2013-01-22 09:43:08
【问题描述】:

我需要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

谁能帮忙?

【问题讨论】:

  • 很好区分不会工作,因为行不是不同的。对于您的要求,宁可在 PHP 中执行此操作,然后在 SQL 语言中执行此操作(带有 pivot 的丑陋子查询)。如果可能,重新设计表结构
  • 您需要从数据库中选择所有行。在 PHP 中打印行时,按 col1 分组。

标签: php mysql select


【解决方案1】:

最简单的方法是从数据库中获取所有行,然后在 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 只是为了简单,不要在生产中使用它们。

【讨论】:

  • 在函数名称中添加“i”会不会让代码变得不那么简单?
  • 非常感谢.. 它的工作原理.. 但为什么不显示

    名称,而是在我身上显示单词“Array”..

【解决方案2】:

你可以这样做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多