php - MySQL 选择所有记录并为每个选择单独的记录 - 在一个查询中

标签 php mysql join

我相信我在这里试图实现的是一个嵌套查询 - 但是我不确定如何继续。

我有 2 个表 usersnotifications 我正在做的是查询 notifications 表以获取详细信息,但是我也是 LEFT OUTER JOIN 在用户表上获取我的用户信息。我拥有的是这样的:

          USERS TABLE     
| user id | username | user image |


    NOTIFICATIONS TABLE  
| receiver id | sender id |

仅获取接收者信息不是问题,因为我使用以下查询:

SELECT
    notifications.senderID, notifications.receiverID, users.username, users.image
FROM
    notifications
    LEFT OUTER JOIN users ON users.id = notifications.receiverID
WHERE notifications.receiverID = ' xxx '

我需要添加的是一种方法,可以为找到的每条记录获取THAT记录的users.username和users.image(对应于users.id for notifications.senderID) 以及主记录(notifications.recieverID)

如果可能,我想将它保留在一个查询中,而不是在 PHP foreach 循环之外。

最佳答案

使用不同的别名两次加入 users

SELECT notifications.senderID, notifications.receiverID, 
       receiver.username as receiver_name, receiver.image as receiver_image,
       sender.username as sender_name, sender.image as sender_image
FROM notifications
LEFT OUTER JOIN users as receiver ON receiver.id = notifications.receiverID
LEFT OUTER JOIN users as sender ON sender.id = notifications.senderID
WHERE notifications.receiverID = ' xxx '

关于php - MySQL 选择所有记录并为每个选择单独的记录 - 在一个查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883072/

相关文章:

sql - 优化具有多个连接的 SQL 查询

php - 如何在邮件主题中设置变音符 ü

php - 有没有办法仅通过数据来了解文件类型

php - 网比 : phpUNit or SimpleTest?

javascript - 如何使用 mysql 将额外的过滤选项添加到 Ajax PHP 搜索

JPA什么时候使用实体类型的Path而不是Join?

sql - 您可以在联接期间更改 where 子句中的列值吗?

php - codeigniter 加入多对多 LIMIT

javascript - 如何通过JSON在MySQL中插入Date类型变量

mysql - 错误的查询得到正确的结果