Jump to content

GROUP BY id and related ID


John84

Recommended Posts

Hi all

I have a database table that looks like the attached image
 

db.JPG.cab4bfa204944d0df95bd2351e98ea7a.JPG

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
                    FROM
                         message
                    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

Results:

Array
(
    [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. Please don't revive it unless you have something important to add.

Join the conversation

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

Guest
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.