Tips to make only One query?
Say开发者_如何学Go I have the following tables:
users
-----
id
username
messages
-----
id
sender (id user)
recipient (id user)
msg
In a single query, how can I get the name of the sender, the name of the recipient, and the message?
I would basically need to join the users table twice, but not sure how that would be possible..
SELECT
s.username as sender,
r.username as recipient,
msg
FROM
messages m join users s on (m.sender = s.id)
join users r on (m.recipient = r.id)
You could use the AS
keyword to give the users
table a different name when you need to join to it:
SELECT `messages`.`id`, `from`.`username`, `to`.`username`, `msg`
FROM `messages`
INNER JOIN `users` AS `from` ON `sender` = `from`.`id`
INNER JOIN `users` AS `to` ON `recipient` = `to`.`id`
精彩评论