Jump to content

GROUP BY id and related ID


Recommended Posts

Hi all

I have a database table that looks like the attached image


This is basically a table of original messages and their replies, the `message_id` is the ID of the original message sent (the master)

How can I perform a group by on both the 'id' and 'message_id' and the sort by ID (newest to oldest)

So in my example it would return the ID's

7 - Message 4
6 - Message 3 Reply 1
4 - Message 1 - Reply 2
3 -Message 2

Any suggestions? I tried GROUP BY id,message_id but that didnt seem to work


Link to comment
Share on other sites

With hierarchical data like this, I find it useful to store the records in an array indexed by parent. For example

$res = $db->query("SELECT id
                         , message_id  as parent
                         , subject
                    ORDER BY message_id, id DESC
$msgs = [];
foreach ($res as $r) {
    $msgs[$r['parent']][] = [ 'id'=>$r['id'], 'subject'=>$r['subject'] ];       // store in array by parent

$results = [];
foreach ($msgs[0] as $m) {                              // loop through parent 0
    if (!isset($msgs[$m['id']])) {
        $latest = $m;                                   // no child messages
    else {
        $latest = $msgs[$m['id']][0];                   // last child message
    $results[$latest['id']] = $latest['subject'];       
krsort($results);                                       // sort ids descending
echo '<pre>', print_r($results, 1), '</pre>';           // show results


    [7] => Message 4
    [6] => Message 3 Reply 1
    [4] => Message 1 Reply 2
    [3] => Message 2


Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.