MySQL查询选择DISTINCT但显示所有行 [英] MySQL query select DISTINCT but display all rows

查看:308
本文介绍了MySQL查询选择DISTINCT但显示所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关DISTINCT的帮助.我想显示不同的行,但还要显示所有行

I need help with 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

任何人都可以帮忙吗?

推荐答案

最简单的方法是从数据库中获取所有行,然后在PHP中对它们进行分组.

The easiest way would be to fetch all rows from the database, and then group them in 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,请勿在生产中使用它们.


Note that I use the deprecated mysql_functions just for simplicity, do not use them in production.

这篇关于MySQL查询选择DISTINCT但显示所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆