我已经为朋友设置了用户在线状态
SELECT * FROM users
WHERE
(id_user IN
(SELECT CASE
WHEN friend_one = '{$id}'
THEN friend_two
WHEN friend_two = '{$id}'
THEN friend_one
END
FROM friends
WHERE status = '1')
) AND (status = '1' OR ($date - last_login) <= 300)
它有效,这个mysql只显示朋友登录状态列表。
但问题是当我尝试创建另一个用户登录状态时,它只显示另一个登录但不在我们的朋友列表中的人的列表。
SELECT * FROM users
WHERE
(id_user NOT IN
(SELECT CASE
WHEN friend_one = '{$id}'
THEN friend_two
WHEN friend_two = '{$id}'
THEN friend_one
END
FROM friends
WHERE status = '1')
) AND (status = '1' OR ($date - last_login) <= 300)
所以这就是我想要的结果
Logged as: khrisna
Friend list: Ben, Alpha, Ralph
All User: Ben, Alpha, John, Mark, Zayn
Online friend list: Ben, Alpha
Another online user: John, Mark, Zayn
有人可以帮助我达到我想要的结果吗?
更新
users
表
friends
表
我想为结果制作类似的东西
在线用户:Khrisna Gunanasurya //登录帐户
在线朋友列表:Alpha,John //登录帐户的在线朋友
其他在线用户:Mark,Ralph //登录的其他用户,而非登录帐户的朋友
答案 0 :(得分:1)
一种方法:
获取所有在线朋友
SELECT *
FROM
(
SELECT CASE WHEN friend_one = ? THEN friend_two ELSE friend_one END friend
FROM friends
WHERE ? IN(friend_one, friend_two)
AND status = 1
) f JOIN users u
ON f.friend = u.id_user
WHERE status = 1 OR last_login >= UNIX_TIMESTAMP() - 300;
获取所有在线的非朋友
SELECT *
FROM users u
WHERE id_user <> ?
AND NOT EXISTS
(
SELECT *
FROM friends
WHERE ? IN(friend_one, friend_two)
AND status = 1
AND u.id_user = CASE WHEN friend_one = ? THEN friend_two ELSE friend_one END
)
AND (status = 1 OR last_login >= UNIX_TIMESTAMP() - 300);
问号表示登录用户的ID值(例如Khrisna Gunanasurya)
这是 SQLFiddle 演示
您的PHP代码可能看起来像
$sql = "SELECT *
FROM
(
SELECT CASE WHEN friend_one = ? THEN friend_two ELSE friend_one END friend
FROM friends
WHERE ? IN(friend_one, friend_two)
AND status = 1
) f JOIN users u
ON f.friend = u.id_user
WHERE status = 1 OR last_login >= UNIX_TIMESTAMP() - 300";
$stmt = $pdo->prepare($sql);
$stmt->execute(array_fill(0, 2, $id));