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

时间:2014-11-12 09:09:22

标签: php mysql join

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

我有2个表用户通知我正在查询通知表以获取详细信息,但我也是 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 '

我需要添加的内容是一种foreach记录的方法,也可以获取 THAT 记录的users.username和users.image(将对应于users.id为notifications.senderID )以及主记录( notifications.recieverID

如果可能我想在一个查询中以及PHP foreach循环之外保留它。

2 个答案:

答案 0 :(得分:2)

使用不同的别名

加入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 '

答案 1 :(得分:0)

这是查询,例如

选择 UseridUserusernameUserpasswordUseremail,{{ 1}}。UserroleUsercreatedUsermodifiedUserdetail,{{1} }。user_idUserdetailfirst_namelast nameUserdetailaddress 来自Userdetailtelephone AS cakephp_test LEFT JOIN usersUser AS cakephp_test ON(userdetailsUserdetail = Userdetailuser_id)WHERE Userid = 51 LIMIT 1

在你的情况下

SELECT notifications.senderID,notifications.receiverID,users.username,users.image FROM database_name.users AS User LEFT JOIN database_name.notification AS notification ON(users.id = notifications.receiverID)WHERE User.id ='xxx'限制1