简单的SQL连接操作

时间:2012-02-11 00:59:54

标签: php mysql join

我的数据库结构如下:

   Members table

   |id|username|...

   Messages table
   |id|fromId|toId|content

在消息表中,id引用消息ID,在成员中它引用用户id(与fromId和toId中的Id相同)。我想做一个连接查询FROM消息WHERE id = SOME_MESSAGE_ID,它提取以下结果集

   |id(message id)|fromId|fromUsername(username that corresponds to fromId)|toId|toUsername(username that corresponds to toId)|content

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

加入成员表两次,但使用不同的别名:

SELECT
    messages.id,
    messages.fromId,
    from_member.username AS fromUsername,
    messages.toId,
    to_member.username AS toUsername,
    messages.content
FROM messages 
JOIN members AS from_member ON from_member.id = message.fromId
JOIN members AS to_member ON to_member.id = message.toId

答案 1 :(得分:1)

这个怎么样:

SELECT    `Message`.`id`,
          `Message`.`fromId`,
          `From`.`username` AS `fromUsername`,
          `Message`.`toId`,
          `To`.`username` AS `toUsername`
          `Message`.`content`
FROM      `Messages` AS `Message`
LEFT JOIN `Members` AS `From`
ON        `From`.`id` = `Message`.`fromId`
LEFT JOIN `Members` AS `To`
ON        `To`.`id` = `Message`.`toId`
WHERE     `Message`.`id` = 1

有关SELECT查询的更多信息,请click here