提示只进行一次查询?

时间:2011-09-14 01:04:01

标签: mysql

说我有以下表格:

users
-----
id
username


messages
-----
id
sender (id user)
recipient (id user)
msg

在单个查询中,我如何获取发件人的姓名,收件人的姓名和邮件?

我基本上需要加入用户表两次,但不确定如何做到这一点..

2 个答案:

答案 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}}