我的数据库中有这个表(关注者)。
follower | following
---------|----------
1 |2
1 |4
1 |5
1 |6
1 |7
1 |8
2 |4
4 |6
此文档记录了我的用户的所有以下内容和关注者。我有这个查询,这是无效的。
SELECT following
FROM followers
WHERE follower
IN (SELECT following
FROM followers
WHERE follower = 2)
OR following IN (SELECT follower
FROM followers
WHERE following = 2)
我想要实现的是用户列表,其后跟用户“2”跟随的用户,与用户“2”后面的用户列表合并。排除所有已经被用户“2”跟随的人。并通过它们与用户“2”的密切关系来安排。
理想情况下,我的数据输出是这个(但不是自动的顺序):
suggested_users
---------------
6
1
5
7
8
我实际上对如何提出这个问题感到茫然,但我如何得到这些结果呢?
答案 0 :(得分:2)
如果你可以选择转储mysql,一些sql变种可以让你使用递归查询来获取树:
http://www.postgresql.org/docs/current/static/queries-with.html
如果没有,有各种解决方案;通常是嵌套集或嵌套间隔:
http://en.wikipedia.org/wiki/Nested_set_model
http://en.wikipedia.org/wiki/Nested_intervals
(SO上有很多关于两者的问题。)
Postgres的声明是什么?我可能会切换,MySQL似乎有点软:P
未经测试,但它类似于:
with recursive tree (root, node) as (
select following as root, follower as node
from followers
union all
select tree.root, followers.follower
from followers
join tree on tree.node = followers.following
)
select * from tree where root = 2;
优化版本如下:
with recursive tree (root, node) as (
select following as root, follower as node
from followers
where following = 2
union all
select tree.root, followers.follower
from followers
join tree on tree.node = followers.following
)
select * from tree;
答案 1 :(得分:0)
这可以通过加入followers
表格来完成。
试试这个:
SELECT f2.following suggested_users
FROM followers f1
INNER JOIN followers f2 ON f2.follower = f1.following
WHERE f1.follower = 2
GROUP BY f2.following
UNION
SELECT f3.follower suggested_users
FROM followers f3
WHERE f3.following = 2
GROUP BY f3.follower
此查询的一般概念是:
f1.follower
跟随f1.following
和f1.following = f2.follower
f2.follower
跟随f2.following
结合
f3.follower
跟在f3.following
和f3.following = 2
表连接将如下所示:
第一个子查询
f1.follower | f1.following = f2.follower | f2.following | suggested_users |
------------|----------------------------|--------------|-----------------|
2 |4 |6 | 6 |
第二个子查询
f3.follower | f3.following | suggested_users |
------------|--------------|-----------------|
1 |2 |1 |