Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips to make only One query?

Tags:

mysql

Say 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..

like image 618
Etienne Avatar asked Mar 10 '26 17:03

Etienne


1 Answers

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)
like image 117
v42 Avatar answered Mar 13 '26 09:03

v42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!