1

我有一个新手 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 |
+----+------------+--------------+--------------------+

我想查询汤姆只有他的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;
    }
}       

任何帮助将不胜感激,

谢谢

4

1 回答 1

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'
于 2012-11-26T03:04:17.133 回答