查找常见的匹配ID

时间:2014-12-05 01:19:07

标签: mysql sql select group-by having

我有一张表(见下文),其中包含一个朋友列表。在每一行中,用户可以是发送者或接收者(请求者/被请求者)。然后状态跟踪他们的关系(状态为1意味着他们是朋友)。但是因为uid可以在发送者或接收者中,所以它会搞砸我。

================================
| sender   | reciever | status |
--------------------------------
| testusr1 | testusr2 | 1      |
| testusr1 | testusr3 | 1      |
| testusr1 | testusr4 | 0      |
| testusr1 | testusr5 | 1      |
| testusr3 | testusr4 | 1      |
| testusr3 | testusr2 | 1      |
| testusr5 | testusr3 | 1      |

所以在上面的例子中,testusr1的朋友是:testusr2,testusr3和testusr5。 testusr3的朋友是:testusr5,testusr4,testusr2,testusr1

我正在寻找的是一个可以获得共同朋友的查询:testusr2和testusr5

从我在这里得到的另一个答案中剔除,我以为我可以做一个工会,但我失去了我追随的逻辑中途......

SELECT f.uid
    FROM(
        (SELECT reciever as uid FROM friends where status=1 and sender='$sentuid')
        UNION 
        (SELECT sender as uid FROM friends where status=1 and reciever='$sentuid')
    ) f
    WHERE ...

非常感谢任何帮助......

3 个答案:

答案 0 :(得分:0)

尝试类似 - (已编辑

SELECT f.uid
FROM (
     SELECT f1.reciever as uid FROM friends f1
     WHERE f1.sender = USER1 AND f1.status = 1
     UNION
     SELECT f2.sender as uid FROM friends f2
     WHERE f2.reciever = USER1 AND f2.status = 1
    ) f
WHERE f.uid IN (
     SELECT f3.reciever as uid FROM friends f3
     WHERE f3.sender = USER3 AND f3.status = 1 AND f3.reciever != USER1
     UNION
     SELECT f4.sender as uid FROM friends f4
     WHERE f4.reciever = USER3 AND f4.status = 1 AND f4.sender != USER1
    );

USER1USER3替换为您想要找到共同朋友的2个用户ID

sqlfiddle示例 - http://sqlfiddle.com/#!2/b0aaf4/8

答案 1 :(得分:0)

这应该可以解决问题。 [增订]

您必须设置发件人和收件人值才能找到共同的朋友。以下查询将找到发件人的共同朋友:testusr1和Receiver:testusr3

set @sender_value=testusr1, @receiver_value=testusr3;

SELECT
    DISTINCT
    F1.Mutual_Friends
  FROM
    (
    SELECT F.sender Mutual_Friends FROM friends F WHERE F.receiver = @sender_value AND F.status = 1
    UNION
    SELECT F.receiver Mutual_Friends FROM friends F WHERE F.sender = @sender_value AND F.status = 1
    ) F1
    INNER JOIN
    (
    SELECT F.sender Mutual_Friends FROM friends F WHERE F.receiver = @receiver_value AND F.status = 1
    UNION
    SELECT F.receiver Mutual_Friends FROM friends F WHERE F.sender = @receiver_value AND F.status = 1
    ) F2 ON
      F2.Mutual_Friends = F1.Mutual_Friends;

答案 2 :(得分:0)

试试这个:

SELECT a.reciever 
FROM (SELECT a.sender, a.reciever 
      FROM tableA a 
      WHERE a.sender IN ('testusr1', 'testusr3') AND a.status = 1
      UNION 
      SELECT a.reciever AS sender, a.sender AS reciever 
      FROM tableA a 
      WHERE a.reciever IN ('testusr1', 'testusr3') AND a.status = 1
     ) AS A 
GROUP BY a.reciever 
HAVING COUNT(DISTINCT a.sender) > 1