【Leetcode1949. 坚定的友谊】使用MySQL在无向图中寻找{"CompleteTripartite", {1, 1, 3}}这个pattern

发布时间 2024-01-13 10:14:52作者: yhm138

题目地址

https://leetcode.cn/problems/strong-friendship/

思路

就是在无向图中寻找这个pattern:

(* Mathematica *)
GraphData[{"CompleteTripartite", {1, 1, 3}}]

SQL写还是比较麻烦。
更加复杂的查询还是建议把数据迁移到neo4j这样的图数据库,然后写Cypher这样的图数据库查询语句。

MySQL代码

with t1 as( -- 图中找到的所有   v1-e1-v2-e2-v3 pattern
    select * from(
        select f1.user2_id as uid , f1.user1_id as one_degree_connected , f2.user1_id as two_degree_connected
        from Friendship f1 
        join Friendship f2 
        on f1.user1_id=f2.user2_id
        union 
        select f1.user2_id as uid , f1.user1_id as one_degree_connected , f2.user2_id as two_degree_connected
        from Friendship f1 
        join Friendship f2 
        on f1.user1_id=f2.user1_id
        union
        select f1.user1_id as uid , f1.user2_id as one_degree_connected , f2.user1_id as two_degree_connected
        from Friendship f1 
        join Friendship f2 
        on f1.user2_id=f2.user2_id
        union 
        select f1.user1_id as uid , f1.user2_id as one_degree_connected , f2.user2_id as two_degree_connected
        from Friendship f1 
        join Friendship f2 
        on f1.user2_id=f2.user1_id
    )tmp1
    where uid<>two_degree_connected and uid<>one_degree_connected and one_degree_connected<>two_degree_connected
    and uid<two_degree_connected
)

select uid as user1_id, two_degree_connected as user2_id
, count(distinct one_degree_connected) as common_friend
from t1

where concat(uid,",",two_degree_connected) in (select concat(user1_id,",",user2_id) from Friendship) -- 坚定的友谊要求这两人还得是朋友

group by user1_id,user2_id
having common_friend>=3
order by user1_id,user2_id,common_friend