我相信我在这里要实现的是嵌套查询 - 但我不确定如何继续。
我有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循环之外保留它。
答案 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)
这是查询,例如
选择
User
。id
,User
。username
,User
。password
,User
。email
,{{ 1}}。User
,role
。User
,created
。User
,modified
。Userdetail
,{{1} }。user_id
,Userdetail
,first_name
。last name
,Userdetail
。address
来自Userdetail
。telephone
AS cakephp_test
LEFT JOIN users
。User
AS cakephp_test
ON(userdetails
。Userdetail
= Userdetail
。user_id
)WHERE User
。id
= 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