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.