开发者

Joining two tables twice in MySQL. Possible or Not???

开发者 https://www.devze.com 2023-03-10 09:13 出处:网络
The table structures for the tables users,messages are like bellow, Users - ID, Name Messages - ID, Sender, Receiver, Message

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

精彩评论

暂无评论...
验证码 换一张
取 消