Jump to content

Recommended Posts

I've been having some problems with left join and grouping, the results are just not working properly.

 

For example... lets say I have 2 tables...

 

table1

----------

id

message

 

table2

----------

id

tid

message

time

 

 

Query...

$query="Select t1.id,t1.message,t2.id,t2.message from table1 t1 left join table2 t2 on t1.id=t2.tid order by time desc";

 

Now, if t2.tid can have multiple entries the same, how do you group them properly so that the entry that has the highest t2.time is chosen and nothing else? I've tried group by t2.tid but it doesn't work.

 

Thank you.

Link to comment
https://forums.phpfreaks.com/topic/177256-solved-left-join-and-grouping-help/
Share on other sites

SELECT
  t1.id,t1.message,t2.id,t2.message
FROM
  table1 AS t1
LEFT JOIN
(
  SELECT 
    t2a.id, t2a.tid, t2a.message, t2a.time
  FROM
    table2 AS t2a
  CROSS JOIN
    (
       SELECT tid, MAX(time) AS time FROM table2 GROUP BY tid 
    ) AS t2b
   USING(tid, time)
) AS t2
ON (t1.id=t2.tid)

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.