Joining two tables twice in MySQL. Possible or Not???
The table structures for the tables users,messages are like bellow,
Users - ID, Name
Messages - ID, Sender, Receiver, Message
I want to join two tables t开发者_高级运维wice like joining the messages.sender with users.id and messages.receiver with users.id.
Is it possible to get the result with sender's id, sender's name, receiver's id, receiver's name, message...(etc) in a single query???...
Yes, you can join the tables as many times as needed.
SELECT
sender.ID AS `sender_id`,
sender.Name AS `sender_name`,
receiver.ID AS `receiver_id`,
receiver.Name AS `receiver_name`,
Messages.Message
FROM
Messages
INNER JOIN
Users AS sender
ON
sender.ID = Messages.Sender
INNER JOIN
Users AS receiver
ON
receiver.ID = Messages.Receiver
Yes you can do it by naming an inner join:
select id, s.Name, r.Name from Messages
inner join users as s on (message.sender = s.id)
inner join users as r on (merssage.receiver = r.id)
精彩评论