0

我的数据库中有这张表(关注者)。

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

我实际上不知道如何提出这个问题,但是我如何得到这些结果呢?

4

2 回答 2

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;
于 2013-06-15T21:53:09.460 回答
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

这个查询的总体思路是:

  1. f1.follower跟随f1.followingf1.following = f2.follower
  2. f2.follower跟随f2.following

结合

  1. f3.follower跟随f3.followingf3.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                |
于 2013-06-15T22:02:42.223 回答