找到我朋友mysql的朋友

时间:2013-12-02 13:29:26

标签: mysql

我有以下表格:

users(id, name) 
friend(friend1,friend2)
images(name, id)
imageliked(imageId,likedId) 

我希望得到我朋友的朋友喜欢的两个选择的图像。 任何人都可以帮助我.....

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT 
  i.*
FROM friend AS f 
INNER JOIN imageLiked AS il ON il.likedId IN(f.friend1, f.friend2)
INNER JOIN images     AS  i ON il.imageId = i.id
WHERE 2 IN(f.friend1, f.friend2); -- 2 is my id for example

请注意:这将包括您喜欢的图片,如果您想删除它们,只需将AND il.likedId <> yourId添加到WHERE子句。


更新

获取您和朋友的朋友所喜欢的图片:

SELECT DISTINCT 
  i.*
FROM 
(
  SELECT f1.friend1 as friend
  FROM friend AS f1
  INNER JOIN
  (
    SELECT friend1
    FROM friend
    WHERE friend2 = 2
    UNION ALL
    SELECT friend2
    FROM friend
    WHERE friend1 = 2
  ) AS f2 ON f2.friend1 IN (f1.friend1, f1.friend2)
  UNION 
  SELECT f1.friend2
  FROM friend AS f1
  INNER JOIN
  (

    SELECT friend1
    FROM friend
    WHERE friend2 = 2
    UNION ALL
    SELECT friend2
    FROM friend
    WHERE friend1 = 2
  ) AS f2 ON f2.friend1 IN (f1.friend1, f1.friend2)
)AS f 
INNER JOIN imageLiked AS il ON il.likedId = f.friend
INNER JOIN images     AS  i ON il.imageId = i.id
WHERE il.likedId <> 2;

仅获取朋友的朋友喜欢的图片:

SELECT DISTINCT 
  i.*
FROM 
(
  SELECT f1.friend2 AS friend
  FROM friend AS f1
  INNER JOIN
  (

    SELECT friend1
    FROM friend
    WHERE friend2 = 2
    UNION ALL
    SELECT friend2
    FROM friend
    WHERE friend1 = 2
  ) AS f2 ON f2.friend1 IN (f1.friend1, f1.friend2)
)AS f 
INNER JOIN imageLiked AS il ON il.likedId = f.friend
INNER JOIN images     AS  i ON il.imageId = i.id
WHERE il.likedId <> 2;