試試這個:
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;
編輯您的問題,並提供樣本數據和所需結果。我不認爲這個查詢做你想要的。 –
另外,我們確實需要查看查詢,因爲它會在您的應用程序代碼解析時看起來像。 '?'並不意味着孤立。 – Strawberry
添加兩個表的完整結構。 –