MYSQL连接以检索结果

时间:2011-12-22 17:31:58

标签: php mysql

我将尝试尽可能地解释我的问题。我正在使用MYSQL / PHP从两个表中获取数据,其结构如下所示:

     table A 
+---------+------------+
| userid  | username   |
+---------+------------+
|    1    |     john   |
|    2    |     doe    |
|    3    |     lewis  |
+---------+------------+

     table B
+---------+------------+-----------+
| id      |from_userid | to_userid |
+---------+------------+-----------+
|    1    |     1      |     3     |
|    2    |     3      |     2     |
|    3    |     1      |     2     |
|    4    |     2      |     1     |
+---------+------------+-----------+

Am trying to achieve the following:

+---------+------------+----------------------+
| id      |sender username| receiver username |
+---------+------------+----------------------+
|    1    |  john         |     lewis         |
|    2    |  lewis        |     doe           |
|    3    |  john         |     doe           |
|    4    |  doe          |     john          |
+---------+------------+----------------------+

如您所见,我不是返回发件人或收件人用户ID,而是根据表A返回其用户名。

我可以在这种情况下使用左连接或右连接吗?提前致谢

2 个答案:

答案 0 :(得分:3)

试试这个

SELECT b.id, sender.username AS sender_username, receiver.username AS receiver_username
FROM tableB AS b
  JOIN tableA AS sender ON b.from_userid = sender.userid
  JOIN tableA AS receiver ON b.to_userid = receiver.userid

答案 1 :(得分:0)

内部连接可以正常工作,你只需要做两个...... 只有当您想从一个表中获取所有记录而从另一个表中获取所有记录时,才需要左和右连接。在这种情况下,您有两个不同的关系,因此需要两个连接。我的MySQL技能有点生疏,所以我不知道'或[是否用作带有空格的表/字段名称的分隔符。

Select t1.ID, T1.userName as 'Sender userName',  T2.username as 'Receiver username'
FROM [Table A] A
INNER JOIN [Table B] T1 
  on T1.from_userid = A.userID
INNER JOIN [Table B] T2 
  on T2.to_userid = A.userID