说我有以下表格:
users
-----
id
username
messages
-----
id
sender (id user)
recipient (id user)
msg
在单个查询中,我如何获取发件人的姓名,收件人的姓名和邮件?
我基本上需要加入用户表两次,但不确定如何做到这一点..
答案 0 :(得分:6)
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)
答案 1 :(得分:5)
当您需要加入AS
关键字时,可以使用users
关键字为SELECT `messages`.`id`, `from`.`username`, `to`.`username`, `msg`
FROM `messages`
INNER JOIN `users` AS `from` ON `sender` = `from`.`id`
INNER JOIN `users` AS `to` ON `recipient` = `to`.`id`
表提供不同的名称:
{{1}}