这是我的疑问:
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查询, - 从用户的所有用户对中获取最后的消息?作为发件人或收件人,并将他们与users表连接以获取名称。我设法创造了这样的东西,但仍然想问是否有更简单的
我想获取我们在收件箱中看到的每个用户的photogrpher名称,个人资料照片和上一条消息。
表 user:profile pic,username,user_id
消息:userid,photographerid,message,timestamp答案 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 = ?
收到消息后,您可以使用user table加入此查询的输出以获取其他列的值,例如:
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;