我有以下表格:
user
+-----------------------------------------------+
| user_id | username | Password | ... |
+-----------------------------------------------+
| 1 | a | *** | ... |
+-----------------------------------------------+
| 2 | b | *** | ... |
+-----------------------------------------------+
| 3 | c | *** | ... |
+-----------------------------------------------+
| 4 | d | *** | ... |
+-----------------------------------------------+
| 5 | e | *** | ... |
+-----------------------------------------------+
friends
+-----------------------------------------------+
| f_id | user_id | friend_id | ... |
+-----------------------------------------------+
| 1 | 4 | 2 | ... |
+-----------------------------------------------+
| 2 | 4 | 1 | ... |
+-----------------------------------------------+
| 3 | 4 | 5 | ... |
+-----------------------------------------------+
| 4 | 4 | 3 | ... |
+-----------------------------------------------+
我想让所有可以添加为好友的用户(在本例中,
user_id
的1
将有3个好友要添加(2, 3, 5)
。但是,通过使用下面的SQL statement below
我只能添加1个用户(4)
:$sql = "SELECT * FROM user WHERE user.user_id NOT IN
(SELECT friends.friend_id FROM friends) AND
user.user_id <> $_SESSION['id']." ORDER BY RAND() LIMIT 5";
但当我以用户4的身份登录时,这非常有用,因为没有可添加的用户。这对我来说有点棘手。任何想法都将非常感谢。
谢谢
最佳答案
编辑:
这个怎么样:
(在ELSE子句中,使用无效的ID或与登录用户相同的ID)
select * from users where id not in
(
select (
case
when uid = 1 then id
when fid = 1 then uid
else 0
end
) from friends where uid = 1 or fid = 1
) and id != 1 order by rand() limit 5;
http://sqlfiddle.com/#!2/12de1/62
另一种解决方法(但可能不是最佳解决方案):
如果用户的好友数小于系统中的用户总数,那么与两个表之间的完全联接相比,下面的联合查询可能不是一个代价高昂的查询。
也不要忘记在
uid
表的fid
和friends
列上添加索引。select * from users where id not in
(
select id from friends where uid = 1
union
select uid from friends where fid = 1
) and id != 1 order by rand() limit 5;
http://sqlfiddle.com/#!2/12de1/40