2017-04-24 63 views
-1

這是我的查詢:試圖在MySQL中獲取最後一條消息

SELECT u.ProfilePic AS FriendPic, u.UserName AS FriendName, m.* 
FROM (SELECT PhotographerId 
     FROM Messages 
     WHERE UserId=? OR PhotographerId=? 
     GROUP BY PhotographerId 
    ) AS m JOIN 
    User AS u 
    ON u.UserId = m.PhotographerId; 

我試圖從表使SQL查詢, - 從所有對與用戶的用戶最後得到的消息?作爲發件人或收件人,並將其與用戶表加入以獲取姓名。我已經成功地創建這樣的事情,但還是要問,如果有更簡單的

我想取photogrpher名,個人檔案相片和每個用戶的最後一條消息,因爲我們在收件箱中看到..

表 用戶:個人檔案相片,用戶名,user_id說明

消息:用戶ID,photographerid,信息,時間戳

+4

編輯您的問題,並提供樣本數據和所需結果。我不認爲這個查詢做你想要的。 –

+0

另外,我們確實需要查看查詢,因爲它會在您的應用程序代碼解析時看起來像。 '?'並不意味着孤立。 – Strawberry

+0

添加兩個表的完整結構。 –

回答

0

試試這個:

SELECT m.userid AS 'User id', u1.profile_pic AS 'User pic', u1.username AS 'User name`, 
m.photographerid AS 'Photographer id', u2.profile_pic AS 'Photographer pic', 
u2.username AS 'Photographer name`, 
m.message, m.timestamp 
FROM message m JOIN user u1 ON m.userid = u1.user_id 
JOIN user u2 ON m.photographerid = u2.user_id 
ORDER BY m.timestamp DESC LIMIT 1; 

更新

你可以得到最新的消息與下面的查詢的用戶:

SELECT m.userid, a.photographerid, m.message, a.timestamp 
FROM message m 
JOIN (SELECT photographerid, MAX(timestamp) as timestamp 
FROM message where userid = ? 
GROUP BY photographerid 
) a 
ON m.photographerid = a.photographerid and m.timestamp = a.timestamp 
WHERE m.userid = ? 

UNION 

SELECT a.userid, m.photographerid, m.message, a.timestamp 
FROM message m 
JOIN (SELECT userid, MAX(timestamp) as timestamp 
FROM message where photographerid = ? 
GROUP BY userid 
) a 
ON m.userid = a.userid and m.timestamp = a.timestamp 
WHERE m.photographerid = ? 

一旦你的消息,你可以加入這個查詢的輸出與用戶表,以獲得其他列的值,例如:

SELECT m.userid AS 'User id', u1.profile_pic AS 'User pic', u1.username AS 'User name`, 
m.photographerid AS 'Photographer id', u2.profile_pic AS 'Photographer pic', 
u2.username AS 'Photographer name`, 
m.message, m.timestamp 
FROM (
    SELECT m.userid, a.photographerid, m.message, a.timestamp 
    FROM message m 
    JOIN (SELECT photographerid, MAX(timestamp) as timestamp 
    FROM message where userid = ? 
    GROUP BY photographerid 
    ) a 
    ON m.photographerid = a.photographerid and m.timestamp = a.timestamp 
    WHERE m.userid = ? 

    UNION 

    SELECT a.userid, m.photographerid, m.message, a.timestamp 
    FROM message m 
    JOIN (SELECT userid, MAX(timestamp) as timestamp 
    FROM message where photographerid = ? 
    GROUP BY userid 
    ) a 
    ON m.userid = a.userid and m.timestamp = a.timestamp 
    WHERE m.photographerid = ? 
) m JOIN user u1 ON m.userid = u1.user_id 
JOIN user u2 ON m.photographerid = u2.user_id; 
+0

你將如何得到最後一條消息,你的查詢會給出所有消息。 –

+0

@AshutoshSIngh這個問題並不完全清楚OP如何排序消息。但是,我已經更新了答案並在其中添加了一個註釋。 –

+0

完全假設的答案,至少很明顯,OP想要獲取用戶的最新消息及其詳細信息。 – Susang

相關問題