My "messages" table has the following fields:
messageid, idto, idfrom, content, and timeSent.
I want my mailbox page to group all of the mails from each individual person (idfrom) and only print the most recent one from each of them. The idea here is that the most recent "conversation" will be at the top of the users mailbox.
I have been googling for hours trying to find a solution. Some claim you need a NATURAL JOIN. Some claim LEFT JOIN. Some have a bunch of frustrating symbols, or "aliases" with no explanation as to where they are defined in your script, e.g. n1.* c2.*.
I have already tried GROUP BY, but it draws randomly (sometimes grabbing older messages and not the most recent one). My current query is below:
"SELECT * FROM messages WHERE idto=$id ORDER BY timeSent DESC LIMIT 100"
Again, using "GROUP BY" will sometimes omit the most recent mail, which is the opposite of what I want.
EDIT: Problem Solved (by not using any additional SQL): Instead of modifying my query, I went with good old PHP and reduced the execution time by a significant amount. Here's how:
Before the "fetch array" loop, I created a variable and made it an empty array ($var = array();)
After that, I made an if statement at the beginning of the FETCH_ARRAY() loop and enclosed all of my previous code into it. (if(!in_array($q['idfrom'], $var))). So, if my user's ID is not already in the array, it will proceed. If it's already there, it will skip on and keep moving through the loop.
At the end of a successful loop (the one that the if statement allowed to pass), I added "array_push($var, $q['idfrom']);"
Meaning, the user's ID is added to the array so that if one of their messages are selected again, the loop skips it.
Viola, it successfully prints the most recent mail from each user with only 3-5 lines of additional PHP code. It's also very modifiable for other purposes as long as your desired condition draws the correct table first, as it will ignore the rest. Make sure your ordering is correct.
I would like to thank everyone for the help and I hope this will save a lot of people a lot of time like it did for me. It was my initial thought, but I felt that using a query may have been the "right" way to do it and decided to ask here.