关于联接的PHP MySQL查询

时间:2012-11-26 02:57:07

标签: php mysql sql

我有一个新手PHP MySQL问题,我有2个表,成员和消息。

表'成员'

+-----------+------+
| MEMBER_ID | NAME |
+-----------+------+
|         1 | Bob  |
|         2 | Ted  |
|         3 | Tom  |
+-----------+------+

表'消息'

+----+------------+--------------+--------------------+
| ID | SENDERS_ID | RECEIVERS_ID |      MESSAGE       |
+----+------------+--------------+--------------------+
|  1 |          1 |            3 | Hello Tom from Bob |
|  2 |          2 |            3 | Hello Tom from Ted |
|  3 |          2 |            1 | Hello Bob from Ted |
+----+------------+--------------+--------------------+

我想查询Tom只有 members.member_id 可用的查询 可以像下面这样获取他的所有邮件以及发件人的姓名:

+------+--------------------+
| name |      message       |
+------+--------------------+
| Bob  | Hello Tom from Bob |
| Ted  | Hello Tom from Ted |
+------+--------------------+

我已经阅读了一些连接的例子,但是知道如何将它们实现到MySQL语句中。

我可以轻松获得Tom的member_id,但不知道如何继续进行。 我还想在数组中返回结果。

  public function getMessages($member_id) {

  $result = mysql_query("SELECT member_id FROM members WHERE member_id = '$member_id'") or die(mysql_error());
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $result = mysql_fetch_array($result); 
        $receivers_id = $result['member_id'];
        .
        // What can I do here to get the $result that I want?
        .
    }
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $results = array();
        while(list($results) = mysql_fetch_array($result)) {
            array_push($results, $result);
        } 
        return $results;
    }
}       

非常感谢任何帮助,

谢谢

1 个答案:

答案 0 :(得分:3)

SELECT  c.name,
        b.message
FROM    members a
        INNER JOIN  messages b
            ON a.member_ID = b.receivers_id
        INNER JOIN members c
            ON b.senders_ID = c.member_ID
WHERE   a.name = 'Tom'