我只想获得单个用户的朋友和每个朋友的结果,以加入用户和朋友之间聊天的最后时间戳:
用户好友列表:
朋友1:fname,lname,....,聊天时间戳
朋友2:fname,lname,....,聊天时间戳
...
users
表是主要的用户信息表:
usr_id,usr_fname,usr_lname
friends
表是一个包含友谊的表:
frd_id,frd_usr_id1,frd_usr_id2
chats
表是一个包含用户之间聊天记录的表:
cht_id,cht_usr_id1,cht_usr_id2,cht_timestamp
任何人都可以帮我处理SQL语句吗?
假设请求用户ID在$ user_id变量中
答案 0 :(得分:0)
试试这个,它应该有用......
SELECT u1.usr_fname [Friend1First],
u1.usr_lname [Friend1Last],
u2.usr_fname [Friend2First],
u2.usr_lname [Friend2Last],
MAX(ch.cht_timestamp) [LastChatTime]
FROM Chats ch
JOIN users u1 ON ch.cht_usr_id1 = u1.usr_id
JOIN users u2 ON ch.cht_usr_id2 = u2.usr_id
WHERE EXISTS (SELECT frd_id from friends fs WHERE (fs.frd_usr_id1 = a.usr_id AND fs.frd_usr_id2 = b.usr_id)
OR (fs.frd_usr_id2 = a.usr_id AND fs.frd_usr_id1 = b.usr_id))
GROUP BY u1.usr_fname, u1.usr_lname, u2.usr_fname, u2.usr_lname,
答案 1 :(得分:0)
这就是答案:
SELECT f.frd_id, u.usr_id, u.usr_fname, u.usr_lname, MAX(c.cht_timestamp)
FROM friends AS f
LEFT JOIN users AS u ON u.usr_id IN (
SELECT u1.usr_id FROM users AS u1 WHERE u1.usr_id != $user_id)
LEFT JOIN chats AS c ON ( (c.cht_usr_id1=$user_id AND c.cht_usr_id2=u.usr_id) OR
(c.cht_usr_id1=u.usr_id AND c.cht_usr_id2=$user_id) )
WHERE ( (f.frd_usr_id1=$user_id AND f.frd_usr_id2=u.usr_id) OR
(f.frd_usr_id1=u.usr_id AND f.frd_usr_id2=$user_id) )
GROUP BY u.usr_id ORDER BY MAX(c.cht_timestamp) DESC