I have a usermessages table in which all messages sent between two users on a site are stored.
Each message has a sourceUserId and a friendId, these are the sender and receiver.
Every user message inbox lists all sent and received messages and each message shows which user has sent or received that message.
The problem
As we are listing sending and receiving users, some columns are the wrong way around, for example if the userId of the current user is 1
- sent messages will have a sourceUserId of 1
- received messages will have a friendId of 1
If I try and do the whole inbox with one query then I have to currently do two joins on both sourceUserId and friendId as I can’t tell which is the currently logged in user.
I already know the username of the currently logged in user so it does not seem right to have two joins when only one is needed?
I am wondering if it is possible to use some sort of case in a mysql query to effectively achieve the following and reduce the amount of data that has to be looked up each time ..
SELECT um.message, UNIX_TIMESTAMP(um.time), um.read, user.username
FROM usermessages um
CASE
WHEN um.friendId = 1
INNER JOIN user ON um.sourceUserId = user.id
WHEN um.sourceUserId = 1
INNER JOIN user ON um.friendId = user.id
END
WHERE (um.friendId = 1 OR um.sourceUserId = 1)
You need to use
CASEforONclause instead(or move the comparison
= user.idinsideCASEif you like it better)