So I have this table
TableTBL:
+--------+------+-------+
| ID | Col1 | Col2 |
+--------+------+-------+
| 1 | A | 30 |
| 2 | A | 20 |
| 3 | B | 40 |
| 4 | A | 10 |
+--------+------+-------+
Now I want to get values from Col2 based off Col1, say I want all the values of A , so the result would be [30, 20, 10] .
I've tried the following query but it doesn't seem to work well:
SELECT DISTINCT Col2 FROM TableTBL WHERE Col1 = 'A' ORDER BY Col2 DESC;
I am using this in php in a foreach loop, so here's the query with the php code:
$sql = "SELECT DISTINCT Col1 FROM TableTBL ORDER BY Col1 DESC;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql ))
{
echo "SQL statement failed";
}
else
{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
$rows[] = $row['Col1'];
}
for($i = 0; $i < count($rows) ;$i++)
{
echo $rows[$i].": {\n";
$sql = "SELECT DISTINCT Col2 FROM TableTBL WHERE Col1 = '$rows[$i]' ORDER BY Col2 DESC;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql))
{
echo "SQL statement failed";
}
else
{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
foreach($rows as $row) {
$arrList[] = $row['Col2'];
}
$text = implode("',' ", array_unique($arrList));
}
}
}
Here $text
is the string containing the result separated by commas.
The problem I am getting here is that I am getting repeated results in all except the first iteration, It is giving me A with 30, 20, 40, 10 , but it then gives me B with 30, 20, 40, 10.
As @Barmar suggested, use a single query:
$sql = "SELECT Col1,
GROUP_CONCAT(DISTINCT Col2 ORDER BY Col2 DESC SEPARATOR ', ') AS Col2
FROM TableTBL
GROUP BY Col1
ORDER BY Col1 ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$arrList = array();
while ($row = mysqli_fetch_assoc($result)) {
$arrList[] = array(
'Col1' => $row['Col1'],
'Col2' => $row['Col2']
);
}
var_export($arrList);
}
OUTPUT :
array(
0 => array(
'Col1' => 'A',
'Col2' => '30, 20, 10',
),
1 => array(
'Col1' => 'B',
'Col2' => '40',
),
)
Check my Demo query .
If you don't know GROUP_CONCAT()
he is a documentation
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.