10

可能重复:
MYSQL 选择共同的朋友

我有一张友谊表,友谊只存储在一行中。所以没有重复的条目。

id  Person1    Person2  status
1         1          2  friend
2         1          3  friend
3         2          3  friend
4         3          4  friend

什么 MySQL 查询(join、inner join)可以帮助我找到第 1 个人和第 3 个人之间的共同(共同)朋友?此示例中的输入是 {1,3},输出应该是 {2},因为 Person #2 是 bot #1 和 #3 的朋友。

4

11 回答 11

9

好吧,到目前为止,唯一可行的查询是 Simon 的……但这确实有点矫枉过正——如此复杂的令人讨厌的查询(2 个子查询和 2 个联合!)对于如此简单的事情,您需要悬赏?:-) 如果您有 1000 多个用户,那么查询会非常慢 - 请记住,它是二次的,并且由于子查询中的联合,几乎不会使用任何索引!

我建议重新考虑设计并允许 2 行重复以建立友谊:

id  Person1    Person2  status
1         1          2  friend
2         2          1  friend
3         1          3  friend
4         3          1  friend

您可能认为这是低效的,但以下简化将允许将查询重写为简单的连接:

select f1.Person2 as common_friend
from friends as f1 join friends as f2
    using (Person2)
where f1.Person1 = '$id1' and f2.Person1 = '$id2' 
    and f1.status = 'friend' and f2.status = 'friend'

这会很快!(不要忘记为 Person1,2 添加索引。)我已经建议在其他非常讨厌的数据结构中进行类似的简化(将子查询重写为联接),它已经加快了从永恒到闪电战的查询!

所以可能看起来很大的开销(一个友谊2行)实际上是一个很大的优化:-)

此外,它还将使诸如“查找 X 的所有朋友”之类的查询更加容易。并且不需要花费更多的赏金:-)

于 2012-04-16T16:45:28.260 回答
2

再来一个答案。

select 
    (case when f1.person1 = 1 then f1.person2 else f1.person1 end) as fid
from friends f1
where f1.person1 = 1 or f1.person2 = 1
and f1.status = 'friend'

intersect

select 
    (case when f1.person1 = 3 then f1.person2 else f1.person1 end) as fid
from friends f1
where f1.person1 = 3 or f1.person2 = 3
and f1.status = 'friend'
于 2012-04-18T18:47:38.987 回答
2

如果这些条件不满足使其工作所需的少量调整,则此查询的工作假设是友谊表中没有自我交友且没有重复。

SELECT fid FROM 
(
    --FIRST PERSON (X) FRIENDLIST
    SELECT 
        (CASE WHEN Person1 = X THEN Person2 ELSE Person1 END) AS fid
    FROM Friendships WHERE (Person1 = X OR Person2 = X) AND status = "friend"
    UNION ALL --DO NOT REMOVE DUPLICATES WITH ALL JOIN
    --SECOND PERSON (Y) FRIENDLIST
    SELECT 
        (CASE WHEN Person1 = Y THEN Person2 ELSE Person1 END) AS fid
    FROM Friendships WHERE (Person1 = Y OR Person2 = Y) AND status = "friend"
) FLIST
GROUP BY fid
HAVING COUNT(*) = 2
于 2012-04-18T14:29:59.273 回答
2
set search_path='tmp';

DROP TABLE friendship CASCADE;
CREATE TABLE friendship
        ( id integer not null PRIMARY KEY
        , person1 integer not null
        , person2 integer not null
        , status varchar
        , CONSTRAINT pk1 UNIQUE (status,person1,person2)
        , CONSTRAINT pk2 UNIQUE (status,person2,person1)
        , CONSTRAINT neq CHECK (person1 <> person2)
        );

INSERT INTO friendship(id,person1,person2,status) VALUES
 (1,1,2,'friend' ) ,(2,1,3,'friend' ) ,(3,2,3,'friend' ) ,(4,3,4,'friend' )
        ;

        -- -----------------------------------------
        -- For implementations that don't have CTEs, 
        -- a view can be used to emulate a CTE.
        -- -----------------------------------------
CREATE VIEW flip AS (
        SELECT person1 AS one
                , person2 AS two
        FROM friendship WHERE status = 'friend'
        UNION
        SELECT person2 AS one
                , person1 AS two
        FROM friendship WHERE status = 'friend'
        );

SELECT DISTINCT
        f1.two AS common
FROM flip f1
JOIN flip f2 ON f1.two = f2.two
WHERE f1.one = 1
AND f2.one = 3
        ;

DROP VIEW flip;

        -- ------------------------------
        -- The same query with a real CTE
        -- ------------------------------
with flip AS (
        SELECT person1 AS one
                , person2 AS two
        FROM friendship WHERE status = 'friend'
        UNION
        SELECT person2 AS one
                , person1 AS two
        FROM friendship WHERE status = 'friend'
        )
SELECT DISTINCT
        f1.two AS common
FROM flip f1
JOIN flip f2 ON f1.two = f2.two
WHERE f1.one = 1
AND f2.one = 3
        ;

结果:

SET
DROP TABLE
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "friendship_pkey" for table "friendship"
NOTICE:  CREATE TABLE / UNIQUE will create implicit index "pk1" for table "friendship"
NOTICE:  CREATE TABLE / UNIQUE will create implicit index "pk2" for table "friendship"
CREATE TABLE
INSERT 0 4
CREATE VIEW
 common 
--------
      2
(1 row)

DROP VIEW
 common 
--------
      2
(1 row)
于 2012-04-18T15:47:27.500 回答
0

内部查询仅获取第一个人的 FRIEND ID,并将其标准化为单个列“FriendID”。如果找到的记录在第一个位置有人员 ID = 1,它会抓取第二个......如果在第二个位置有人员 ID = 1,那么它会抓取第一个。

完成后,我们知道谁是第 1 个人的唯一朋友列表……完成。现在,再次加入友谊表,但仅限于那些 FIRST 有资格成为第 1 个人的朋友之一的人......一旦有资格,然后确保第二张桌子上的另一个人是第 3 个人你在寻找共同点。

确保在 person1 和 person2 上都有一个索引,以利用 OR 条件。

select
      JustPerson1Friends.FriendID
   from
      ( select
              if( f.Person1 = 1, f.Person2, f.Person1 ) as FriendID
           from
              Friendships f
           where
                   (    f.Person1 = 1
                     OR f.Person2 = 1 )
               AND f.status = "friend" ) JustPerson1Friends
      JOIN Friendships f2
         on  (   JustPerson1Friends.FriendID = f2.Person1
              OR JustPerson1Friends.FriendID = f2.Person2 )
         AND f2.status = "friend"
         AND ( f2.Person1 = 3 OR f2.person2 = 3 )

另一种选择将人“3”作为常见的人预先标记到结果集中,因此我们以后不需要明确限定 3。此外,通过使用 MySQL 变量,易于编写脚本并作为参数实现。在内部查询之后,对友谊进行 DOUBLE left-join 以明确测试可以在 X/Y 或 Y/X 组合中找到一个人的 BOTH 组合。所以最后的 where 子句只是说只要在 EITHER LEFT-JOIN 条件中找到一条记录,它就是一个共同的朋友并包含在结果集中。

select
      JustPerson1Friends.FriendID
   from
      ( select
              @WantPerson2 as FindInCommonWith,
              if( f.Person1 = @WantPerson1, f.Person2, f.Person1 ) as FriendID
           from
              ( select @WantPerson1 := 1,
                       @WantPerson2 := 3 ) sqlvars
              Friendships f,
              (
           where
                   (    f.Person1 = @WantPerson1
                     OR f.Person2 = @WantPerson2 )
               AND f.status = "friend" ) JustPerson1Friends

      LEFT JOIN Friendships f2
         on JustPerson1Friends.FindInCommonWith = f2.Person1
         AND JustPerson1Friends.FriendID = f2.Person2
         AND f2.status = "friend"

      LEFT JOIN Friendships f3
         on JustPerson1Friends.FindInCommonWith = f2.Person2
         AND JustPerson1Friends.FriendID = f2.Person1
         AND f2.status = "friend"
   where
         f2.Person1 > 0
      OR f3.Person1 > 0
于 2012-04-17T23:24:06.730 回答
0

如果各种回复或评论之一已经提出了这一点,我深表歉意,但是如何:

select Person2 mutual_friend from 
  (select Person1, Person2 from friends 
      where Person1 in (1,3) union 
   select Person2, Person1 from friends 
      where Person2 in (1,3)
  ) t 
  group by Person2 having count(*) > 1;
于 2012-04-16T18:13:09.310 回答
0

此查询返回 '22' 作为结果,因为它对于 1 和 3 都很常见 您可能必须过滤掉不同的 PERSON1/PERSON2 如果我可以优化此查询,我会更新它


SELECT DISTINCT (REPLACE(TRANSLATE((WM_CONCAT(DISTINCT F.PERSON1) || ',' ||
                                           WM_CONCAT(DISTINCT F.PERSON2)),
                                           '1,3',
                                           ' '),
                                 ' ',
                                 '')) AS COMMON_FRIEND
          FROM FRIENDSHIP F
         WHERE UPPER(F.STATUS) = 'FRIEND'
         AND ((SELECT DISTINCT WM_CONCAT(F1.PERSON1)
                   FROM FRIENDSHIP F1
                  WHERE F1.PERSON2 = '3') LIKE ('%' || F.PERSON1 || '%') OR
               (SELECT DISTINCT WM_CONCAT(F1.PERSON2)
                   FROM FRIENDSHIP F1
                  WHERE F1.PERSON1 = '3') LIKE ('%' || F.PERSON2 || '%'))
           AND ((SELECT DISTINCT WM_CONCAT(F1.PERSON1)
                   FROM FRIENDSHIP F1
                  WHERE F1.PERSON2 = '1') LIKE ('%' || F.PERSON1 || '%') OR
               (SELECT DISTINCT WM_CONCAT(F1.PERSON2)
                   FROM FRIENDSHIP F1
                  WHERE F1.PERSON1 = '1') LIKE ('%' || F.PERSON2 || '%'))
           AND NOT ((F.PERSON1 = '1' AND F.PERSON2 = '3') OR
                (F.PERSON1 = '3' AND F.PERSON2 = '1'))

于 2012-04-19T05:34:39.720 回答
0

我认为这很简单

SELECT * FROM friends

WHERE
     (Person1 = '1' or Person2 = '1') && 
     (Person1 = '2' or Person2 = '2') &&
     status = 'friend'

鉴于您正试图在人 1 和 2 之间找到相互

于 2012-04-06T12:18:02.200 回答
0

我问过编号较小的用户是否总是Person1,但我最后写了一个不关心是否属实的查询。

set @firstParty = 1, @secondParty = 3

select friends_of_first.friend
from (
    select Person2 as friend from friends where Person1 = @firstParty
    union 
    select Person1 as friend from friends where Person2 = @firstParty
    ) as friends_of_first
join (
    select Person2 as friend from friends where Person1 = @secondParty
    union 
    select Person1 as friend from friends where Person2 = @secondParty
    ) as friends_of_second
on friends_of_first.friend = friends_of_second.friend

查找用户朋友的子查询可以替换为@NirmalthInk beYond 使用的子查询:

select case when f1.person1 = @firstParty then  f1.person2 else f1.person1 end 
from friend f1 where f1.person1 = @firstParty or f1.person2 = @firstParty

我很想知道哪种替代方案表现更好。

于 2012-04-16T16:09:18.917 回答
-1
id  Person1    Person2  status
1         1          2  friend
2         1          3  friend
3         2          3  friend
4         3          4  friend


  SELECT
    DISTINCT
    F1.Person
  FROM
    --Friends of 1
    (
    SELECT F.Person1 Person FROM People F WHERE F.Person2 = 1 AND F.status = 'friend'
    UNION
    SELECT F.Person2 Person FROM People F WHERE F.Person1 = 1 AND F.status = 'friend'
    ) F1
    INNER JOIN
    (
    --Friends of 3
    SELECT F.Person1 Person FROM People F WHERE F.Person2 = 3 AND F.status = 'friend'
    UNION
    SELECT F.Person2 Person FROM People F WHERE F.Person1 = 3 AND F.status = 'friend'
    ) F2 ON
      F2.Person = F1.Person

输出:

Person
2
于 2012-04-19T14:49:59.067 回答
-1

这应该回答您当前的问题,尽管我建议不要这样做。在这种情况下,我总是选择存储两个关系副本,每个方向一个。

SELECT IF(f1.person1 IN ($id1, $id3), f1.person2, f1.person1) AS mutual_friend
FROM friends f1
INNER JOIN friends f2
    ON (f1.person1 = $id1 AND f2.person1 = $id3 AND f1.person2 = f2.person2)
    OR (f1.person1 = $id1 AND f2.person2 = $id3 AND f1.person2 = f2.person1)
    OR (f1.person2 = $id1 AND f2.person1 = $id3 AND f1.person1 = f2.person2)
    OR (f1.person2 = $id1 AND f2.person2 = $id3 AND f1.person1 = f2.person1)
WHERE f1.status = 'friend' AND f2.status = 'friend'
于 2012-04-06T13:00:46.193 回答