我正在构建一个聊天应用程序,我希望列出最近发送消息的用户及其id, name, pic, and last message (id, timestamp, content)
我的两张桌子看起来像这样:
users:
------
id
name
pic
messages:
---------
id
content
timestamp
user_id (foreign key of user's id)
以下是我尝试的查询:
SELECT U.*,
MAX(M.id) as lastmessage_id
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC
它会列出最近收到消息的用户,但不包含最后一封消息的“内容”
当前输出:
id, name, pic, lastmessage_id
必需的输出:
id, name, pic, lastmessage_id, lastmessage_content, lastmessage_timestamp
答案 0 :(得分:1)
首先找到每个用户的所有最新消息ID,然后将其与消息表连接以获取相应的行:
select u.*,
m.*
from users u
join messages m on u.id = m.user_id
join (
select user_id,
max(id) as id
from messages
group by user_id
) t on m.id = t.id
and m.user_id = t.user_id
order by m.id desc;
此外,始终使用显式现代连接语法而不是旧的基于逗号的语法。
答案 1 :(得分:1)
func gotoNextVC() {
let destinationVC = YourViewController(nibName: "YourViewController", bundle: nil)
destinationVC.userAcount = self.userAcount
self.navigationController?.pushViewController(destinationVC, animated: true)
// OR
self.present(destinationVC, animated: true, completion: nil)
}
答案 2 :(得分:0)
试试这个......
select t1.id,t1.name,t1.pic,t1.lastmessage_id from (SELECT U.id,U.name,U.pic,(M.id) as lastmessage_id FROM users U, messages M WHERE M.user_id=U.id ORDER BY lastmessage_id DESC) t1
GROUP BY t1.id
答案 3 :(得分:0)
在脚本中,显示users表中的所有列,但只显示messages表中的id。将脚本更改为低于1。
SELECT U.*,
MAX(M.id) as lastmessage_id , M.content, M.timestamp
FROM users U, messages M
WHERE M.user_id=U.id
GROUP BY user_id
ORDER BY lastmessage_id DESC
答案 4 :(得分:0)
尝试使用JOIN:
SELECT U.*, MAX(M.id) AS lastmessage_id
FROM users U
JOIN MESSAGES M ON U.id = M.user_id
GROUP BY user_id
ORDER BY lastmessage_id DESC