My database structure is like this:
Members table
|id|username|...
Messages table
|id|fromId|toId|content
In the messages table id refers to the message ID, in the members it refers to the user id (which is the same Id that is in fromId and toId). I want to do a join query FROM messages WHERE id=SOME_MESSAGE_ID that pulls the following result set
|id(message id)|fromId|fromUsername(username that corresponds to fromId)|toId|toUsername(username that corresponds to toId)|content
Any help would be appreciated.
Join the members table twice but using different aliases:
SELECT
messages.id,
messages.fromId,
from_member.username AS fromUsername,
messages.toId,
to_member.username AS toUsername,
messages.content
FROM messages
JOIN members AS from_member ON from_member.id = message.fromId
JOIN members AS to_member ON to_member.id = message.toId
How about this:
SELECT `Message`.`id`,
`Message`.`fromId`,
`From`.`username` AS `fromUsername`,
`Message`.`toId`,
`To`.`username` AS `toUsername`
`Message`.`content`
FROM `Messages` AS `Message`
LEFT JOIN `Members` AS `From`
ON `From`.`id` = `Message`.`fromId`
LEFT JOIN `Members` AS `To`
ON `To`.`id` = `Message`.`toId`
WHERE `Message`.`id` = 1
For more information on SELECT queries, click here.