表用户的表结构,消息如下所示,
Users - ID, Name
Messages - ID, Sender, Receiver, Message
我想连接两个表两次,比如使用users.id加入messages.sender,使用users.id加入messages.receiver。
是否有可能在单个查询中以发件人的ID,发件人姓名,收件人ID,收件人姓名,邮件......(等)获得结果??? ...
答案 0 :(得分:4)
是的,您可以根据需要多次加入表格。
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
答案 1 :(得分:3)
是的,您可以通过命名内部联接来实现:
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)