SQLite:如何看待那些不是我的朋友,而是我朋友的朋友
我在DB浏览器中有一个数据库,其中有两个表SQLite:如何看待那些不是我的朋友,而是我朋友的朋友,sql,sqlite,inner-join,where-clause,Sql,Sqlite,Inner Join,Where Clause,我在DB浏览器中有一个数据库,其中有两个表 CREATE TABLE "User" ( "ID" integer NOT NULL, "name" TEXT NOT NULL, PRIMARY KEY("ID" AUTOINCREMENT) ); 所以我的问题是,我如何做一个查询来显示我不是朋友但我的朋友是他们的朋友。这样我基本上可以找到新朋友。您可以多次加入: select dis
CREATE TABLE "User" (
"ID" integer NOT NULL,
"name" TEXT NOT NULL,
PRIMARY KEY("ID" AUTOINCREMENT)
);
所以我的问题是,我如何做一个查询来显示我不是朋友但我的朋友是他们的朋友。这样我基本上可以找到新朋友。您可以多次加入:
select distinct u.id, u.name
from friends f1 -- my friends
inner join friends f2 on f2.userid = f1.friendid -- the friends of my friends
inner join users u on u.id = f2.friendid
where
f1.userid = ?
and f2.friendid <> f1.userid
and not exists ( -- that are not my friends
select 1 from friends f3 where f3.userid = ? and f3.friendid = f2.frienid
)
非常感谢,当我运行代码时,它列出了我朋友的所有朋友,但它也列出了需要我提供信息的用户,我只想列出朋友的朋友,而不是我自己。有没有简单的解决方法?@NotImpostor:我们可以在where子句中使用另一个条件。我更新了我的答案。我通过无意的粘贴和发布,解开了最有可能是意外编辑的内容。
select distinct u.id, u.name
from friends f1 -- my friends
inner join friends f2 on f2.userid = f1.friendid -- the friends of my friends
inner join users u on u.id = f2.friendid
where
f1.userid = ?
and f2.friendid <> f1.userid
and not exists ( -- that are not my friends
select 1 from friends f3 where f3.userid = ? and f3.friendid = f2.frienid
)