简体   繁体   中英

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 twice 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM