簡體   English   中英

MySQL選擇所有記錄,並為每個選擇單獨的記錄-在一個查詢中

[英]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 idUser username User passwordUser emailUser roleUser createdUser modifiedUserdetail user_idUserdetail first_namelast nameUserdetail addressUserdetail telephone來自cakephp_test users作為User LEFT cakephp_test userdetails AS Userdetail ON( Userdetailuser_id = Userid )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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM