Jump to content

display max value when GROUP BY


MDanz

Recommended Posts

Ok, as easiest as i can explain.

 

 


  •  
  • There are many child.sid to parent.id.
     
  • There are many child.nid to child.sid
     
  • There are many child.id to child.nid

 

child.id is just the id of a child row. And each row has rating column.

 

In the query i'm grouping by child.nid. But the results that are being returned are the first entry(lowest child.id) for each nid. What i want is the highest rated child.id for that nid.

 

$construct =  "SELECT child.* FROM outcomes child 
    JOIN outcomes parent on parent.id=child.sid JOIN    
    WHERE (parent.name LIKE '%$search%') GROUP BY child.nid,child.sid
    ORDER BY child.rating DESC";

 

I've tried ORDER BY child.rating DESC but this needs to happen before the GROUP BY child.nid.

 

Any idea how to solve this problem?

 

Link to comment
Share on other sites

Hi

 

You will probably need to use a subselect to get the relevant sub rows.

 

Ie, something like (and this will be wrong as I am not 100% clear on what you want):-

 

SELECT *
FROM outcomes parent
INNER JOIN outcomes child ON parent.id=child.sid
INNER JOIN (SELECT nid, MAX(id) AS ChildId FROM outcomes GROUP BY nid) ChildMax ON child.nid = ChildMax.nid
INNER JOIN outcomes child2 ON ChildMax.ChildId = child2.id

 

Ie, find the max id you are interested in, grouped by the relevant field, and then join that back against the table to get the other fields from that row.

 

While you are getting the highest rated child id, that is probably not certain (ie, the row is probably random).

 

However I can't give any more info as your example SQL is only half there

 

All the best

 

Keith

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.