我是下表:
朋友:
id | user1 | user2 | status
1 | Jorge | Alisson | 3
2 | Lucas | Jorge | 3
要做SELECT
,我做(变量$userLogged
指的是当时登录的用户):
SELECT user1, user2, status
FROM friends
WHERE user1 = '$userLogged' OR user2 = '$userLogged'
所以,在PHP中:
foreach($query as $q) {
if($q["user1"] == $userLogged) {
$userFriend = $q["user2"];
} else {
$userFriend = $q["user1"];
}
}
假设$userLogged
是Jorge。我想得到朋友($userFriend
),即不是$userLogged
(Alisson和Lucas,以防万一)。目前我使用PHP以上面显示的方式进行检查。如何在查询中直接执行此操作,从而在PHP中保存此检查?例如:SELECT user1 AND user2 <> '$userLogged' AS userFriend
...
答案 0 :(得分:2)
如果您有friends(user1, user2, status)
和friends(user2, user1, status)
的索引,那么最快的方式是:
SELECT user2 as `user`, status
FROM friends
WHERE user1 = '$userLogged'
UNION ALL
SELECT user1, status
FROM friends
WHERE user2 = '$userLogged';
索引可以用于两个子查询,所以这应该非常快。
答案 1 :(得分:1)
User