php - MYSQL 连接检索结果

标签 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 返回他们的用户名。

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

最佳答案

试试这个

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

关于php - MYSQL 连接检索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8607701/

相关文章:

php mysql 连接并创建表,没有错误,但没有数据

php - MySQL 中的 NPV 计算

mysql - 我正在加入三个表,但我想将其中一个表的值分别用于其他两个表

python - UnpicklingError 加载 key 无效, '{'

php - 为什么在 CURLOPT_COOKIESSION 设置为默认值时需要 CURLOPT_COOKIEJAR

php - 如何检索mysql数据并将其显示在html中

php - 交响乐 4 : WebTestCase fails (Failed to start the session)

python - 如何使用pyqt获取表中的选定项目?

php - 奇怪的准备语句错误

php - 使用foreach循环将数据插入mysql数据库