SQL的相互喜欢

时间:2019-01-07 00:07:06

标签: sql postgresql

match
---
id person_1_id persona_2_id liked
9  1           2            true
10 1           3            false
11 2           1            true
12 2           3            true
13 3           1            false
14 3           2            false

person_1_id是喜欢的人,person_2_id是被喜欢的人。

我将如何查询person id = 1的共同点?意思是person_1_id = 1喜欢person_2_id,而persona_2_id喜欢它们。预期结果将是包含person_id = 2的一行。

3 个答案:

答案 0 :(得分:2)

使用自联接:

SELECT DISTINCT t1.person_1_id, t1.person_2_id
FROM mytable t1
INNER JOIN mytable t2 
    ON t1.person_1_id = t2.person_2_id 
    AND t1.person_2_id = t2.person_1_id
    AND t2.liked = true
WHERE t1.liked = true;

或具有EXISTS条件的相关子查询:

SELECT DISTINCT t1.person_1_id, t1.person_2_id
FROM mytable t1
WHERE 
    EXISTS (
        SELECT 1 
        FROM mytable t2 
        WHERE 
            t1.person_1_id = t2.person_2_id 
            AND t1.person_2_id = t2.person_1_id
            AND t2.liked = true
    )
    AND t1.liked = true;

答案 1 :(得分:1)

此查询将为您提供所需的结果。它会寻找person_id 1喜欢的任何人,同时也喜欢他们:

SELECT persona_2_id
FROM match m
WHERE person_1_id = 1 AND
      liked = true AND
      EXISTS (SELECT *
              FROM match m1
              WHERE m1.person_1_id = m.persona_2_id AND
                    m1.persona_2_id = m.person_1_id AND
                    m1.liked = true)

输出:

persona_2_id
2

Demo on dbfiddle

答案 2 :(得分:0)

您可以使用exist子句

SELECT DISTINCT t1.person_1_id, t1.person_2_id
from tbl t1
where exists (select null from tbl t2
  where t1.person_1_id = t2.person_2_.id and
     t1.person_2_id = t2.person_1_id and
     t2.liked = true
) and t1.liked = true;

如果您只想查询person_1_id = 1,则只需在末尾添加and t1.person_1_id = 1