I have a simple messaging system, and I’d like to display both Received and Sent messages. The relevant tables/columns are laid out as follows, with extraneous information omitted:
User:
id | firstName | lastName
-------------------------
Message:
id | fromid | toid | message
----------------------------
The query I’m running is:
SELECT message.id, `fromid`, `toid`, `sent`, `message`, message.email, `read`, user.id, `firstName`, `lastName`, `rank`
FROM message LEFT JOIN `user` ON message.fromid = user.id OR message.toid = user.id
WHERE `toid` = '$id' OR `fromid` = '$id'
ORDER BY `read` DESC, `sent` DESC";
(And for sorting in my PHP script, I do:)
$received = array();
$sent = array();
while ($dbRow = mysql_fetch_array($query)) {
if ($dbRow['toid'] == $id) {
$received[] = $dbRow;
} else if ($dbRow['fromid'] == $id) {
$sent[] = $dbRow;
}
}
So what I want to do select the messages where either toid or fromid are equal to the user’s id, then sort them accordingly (i.e., if the user’s id is in the toid column, it was sent from other user to them, whereas if it’s in the fromid column, the user had sent it to somebody else).
The query almost kind of works, except the $sent[] array contains duplicates: it lists each row twice, once displaying the user’s name and the other displays the receiver’s name. I can kind of see why, but I don’t know what to do to fix it.
I don’t know if I need to adjust my SQL query or my PHP script, so I’ve included both.
I know I could just break it up into two queries, but I’m trying to improve on my SQL and learn more about how JOINs work.
Do two joins – in other words, join the user table one for the “from” and another time for “to”, something like this: