首页 > 解决方案 > 查询以获取所有用户 Y 的兴趣主题,其中 Y 与用户 X 共享 >=3 个兴趣

问题描述

这是来自假定的 Twitter 数据库的一部分的两个表,用户可以在其中关注其他用户。User.name 字段是唯一的。

mysql> select uID, name from User;
+-----+-------------------+
| uID | name              |
+-----+-------------------+
|   1 | Alice             |
|   2 | Bob               |
|   5 | Iron Maiden       |
|   4 | Judas Priest      |
|   6 | Lesser Known Band |
|   3 | Metallica         |
+-----+-------------------+
6 rows in set (0.00 sec)

mysql> select * from Follower;
+-----------+------------+
| subjectID | observerID |
+-----------+------------+
|         3 |          1 |
|         4 |          1 |
|         5 |          1 |
|         6 |          1 |
|         3 |          2 |
|         4 |          2 |
|         5 |          2 |
+-----------+------------+
7 rows in set (0.00 sec)

mysql> call newFollowSuggestionsForName('Bob');
+-------------------+
| name              |
+-------------------+
| Lesser Known Band |
+-------------------+
1 row in set (0.00 sec)

我想做一个操作,为用户 X 建议他们可能有兴趣关注的用户列表。我认为一种启发式方法可能是向所有 y 显示用户 y 关注的 X,其中 X 和 y 至少关注 3 个相同的用户。下面是我想出的用于执行此操作的 SQL。我的问题是它是否可以通过其他方式更有效或更好地完成。

DELIMITER //
CREATE PROCEDURE newFollowSuggestionsForName(IN in_name CHAR(60))
BEGIN

DECLARE xuid INT;
SET xuid = (select uID from User where name=in_name);  

select name
from User, (select subjectID
            from follower
            where observerID in (
                select observerID
                from Follower
                where observerID<>xuid and subjectID in (select subjectID from Follower where observerID=xuid)
                group by observerID
                having count(*)>=3
            )
    ) as T
where uID = T.subjectID and not exists (select * from Follower where subjectID=T.subjectID and observerID=xuid);

END //
DELIMITER ;

标签: mysqlsql

解决方案


我认为基本查询从获取与给定观察者共享三个“主题”的所有“观察者”开始:

select f.observerid
from followers f join
     followers f2
     on f.subjectid = f2.subjectid and
        f2.observerid = 2
group by f.observerid
having count(*) = 3;

查询的其余部分只是加入名称以适应您使用名称而不是 id 进行引用的范例。


推荐阅读