I have a MYSQL database with some columns and rows. And I want to select some of rows with same value and sum them and then sort them.
for example:
Id data
1 5
2 12
4 42
2 2
1 3
1 8
4 2
something like : data : (16 id : 1) , (data : 14 id : 2) , (data : 44 id : 4)
for doing this I tried this code :
$sql = "SELECT id, SUM(data) AS value_sum FROM table GROUP BY id ORDER BY value_sum DESC LIMIT 30";
$result = mysqli_query($conn, $sql);
$ids = "";
$datas = "";
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result))
{
$ids .= $row['p_id'] . '^';
$datas.= $row['value_sum'] . '^';
}
}
And it works fine and I can get sum of rows values sorted as value_sum.
But my problem is the ids are not sorted and I want to get sorted ids too but the result is not sorted.
I mean in the result i don't know can I get true id for value_sum.
for more explanation I want this result :
(id 4 : 44) , (id 1 : 16) , (id 2 : 14)
How can I do this ?