[英]MySQL selecting all records and for each select separate record - in one query
我相信我要在這里實現的是嵌套查詢-但是我不確定如何繼續。
我有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 '
我需要添加的一種方法是,對找到的每個記錄也抓取THAT記錄的users.username和users.image( 將與notifications.senderID的users.id相對應 )以及主記錄( 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 '
例如,這是查詢
SELECT User
。 id
, User
。 username
User
。 password
, User
。 email
, User
。 role
, User
。 created
, User
。 modified
, Userdetail
。 user_id
, Userdetail
。 first_name
, last name
, Userdetail
。 address
, Userdetail
。 telephone
來自cakephp_test
。 users
作為User
LEFT cakephp_test
。 userdetails
AS Userdetail
ON( Userdetail
。 user_id
= User
。 id
)WHERE User
。 id
= 51 LIMIT 1
在你的情況下
SELECT notifications.senderID,notifications.receiverID,users.username,users.image FROM database_name.users AS用戶LEFT JOIN database_name.notification AS通知ON(users.id = notifications.receiverID)WHERE User.id ='xxx'LIMIT 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.