php – MySQL – NOT IN产生不需要的结果
作者:互联网
我有以下表格:
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语句我只获得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登录时没有用户可以添加,这种方法很有效.这对我来说有点棘手.任何想法都将非常感激.
谢谢
解决方法:
编辑:
这个怎么样:
(in 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列上添加索引.
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
标签:notin,not-exists,php,mysql,join 来源: https://codeday.me/bug/20190901/1782381.html