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
Can anyone help?
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 />";
}
}
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.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.