检索2个连接表的类似列

时间:2015-08-08 10:18:06

标签: mysql sql

我需要获得2个用户的所有共同朋友(dummy4和虚拟5) 然后检索他们所有的fname,lname和个人资料图片。

USER_INFO

fabric.PathGroup.prototype.isSameColor = function() {
var firstPathFill = this.getObjects()[0].get('fill') || '';
  if (typeof firstPathFill !== 'string') {
    return false;
  }
  firstPathFill = firstPathFill.toLowerCase();
  return this.getObjects().every(function(path) {
    var pathFill = path.get('fill') || '';
    return typeof pathFill === 'string' && (pathFill).toLowerCase() === firstPathFill;
   });
 };
朋友

id    fname      lname     profile_pic

1     barrack    obama     1.jpg
2     tom        jones     2.jpg
3     dummy1     dummy1    3.jpg
4     dummy2     dummy2    4.jpg
5     dummy3     dummy3    5.jpg
6     dummy4     dummy4    6.jpg

这是我试过的查询

counter     user_id        friend_id      request_status
1           2              1              friend
2           4              5              friend
3           3              4              friend
4           5              3              friend
5           1              6              waiting
6           6              3              friend
7           1              3              friend
8           2              6              waiting
9           1              4              friend
10          3              2              friend
11          5              1              canceled
12          4              6              friend

但它什么也没有返回。

我想让结果像这样

SELECT profile_pic, fname, lname FROM 
user_info JOIN friend ON 
(friend.friend_id = user_info.id OR friend.user_id = user_info.id) AND
((friend.user_id = 3 OR friend.friend_id = 4) AND 
(friend.user_id = 4 OR friend.friend_id = 3))
AND friend.request = 'friend' GROUP BY user_info.id

2 个答案:

答案 0 :(得分:1)

如何使用exists

SELECT u.*
FROM user_info u
WHERE EXISTS (SELECT 1
              FROM friend f
              WHERE u.id IN (f.user_id, f.friend_id) AND
                    $friend1 IN (f.user_id, f.friend_id) AND
                    f.request_status = 'friend'
             ) AND
      EXISTS (SELECT 1
              FROM friend f
              WHERE u.id IN (f.user_id, f.friend_id) AND
                    $friend2 IN (f.user_id, f.friend_id) AND
                    f.request_status = 'friend'
             ) AND
      u.id NOT IN ($friend1, $friend2);

我不确定你是如何代表朋友的。没有什么叫做'#34; dummy5"在您的示例数据中,它们仅由上述代码中的变量表示。

答案 1 :(得分:0)

SELECT profile_pic, fname, lname
FROM user_info u
WHERE u.`id` IN(
   SELECT DISTINCT IF(f1.`user_id`=4,f1.`friend_id`,f1.`user_id`) as mutfri
   FROM friend as f1
   WHERE IF(f1.`user_id`=4,f1.`friend_id`,f1.`user_id`) IN(
      SELECT IF(f2.`user_id`=3, f2.`friend_id`, f2.`user_id`) as friend_id
      FROM friend as f2
      WHERE f2.`request_status` = 'friend' AND (f2.`user_id` = 3 OR f2.`friend_id` = 3)
   ) AND f1.`request_status`='friend' AND (f1.`user_id` = 4 OR f1.`friend_id` = 4)
);

这是一个解决方案,不使用子查询(synchronized subquerys)中的外部查询中的列。因此它在更大的数据库上具有更好的性能。