【问题标题】:SQL QUERY Check if user Liked each otherSQL QUERY 检查用户是否互相喜欢
【发布时间】:2021-04-03 14:41:22
【问题描述】:

我有一个名为 match_liked 的 sql 表,其中包含 3 个数据:iduser_idmatch_id

+----+---------+----------+
| id | user_id | match_id |
+----+---------+----------|
|  1 |     100 |       63 |
|  2 |      63 |       100|
|  3 |      45 |       77 |
|  4 |      11 |       44 |
|  5 |      33 |       2  |
+----+------+-------------+

你可以看到超过 100 个喜欢的 63 和 63 个也喜欢 100 所以我想选择所有我试过的:

SELECT * from match_liked WHERE user_id = 100 AND match_id = 63 AND user_id = 63 AND match_id = 100

但它不起作用,那么检查两个用户是否相互喜欢的正确查询是什么?

【问题讨论】:

    标签: mysql sql select many-to-many where-clause


    【解决方案1】:

    你可以使用自我加入,

    select o1.* from match_liked o1 inner join match_liked o2
       on o1.user_id  = o2.match_id or o1.match_id = o2.user_id
    

    【讨论】:

      【解决方案2】:

      一种方法使用exists

      select ml.*
      from match_liked ml
      where exists (select 1
                    from match_liked ml2
                    where ml2.user_id = ml.match_id and ml2.match_id = ml2.user_id
                   );
      

      假设你没有重复,你也可以使用聚合:

      select least(user_id, match_id), greatest(user_id, match_id)
      from match_liked
      group by least(user_id, match_id), greatest(user_id, match_id)
      having count(*) = 2;
      

      【讨论】:

        猜你喜欢
        • 2017-09-06
        • 2018-10-13
        • 1970-01-01
        • 2013-01-03
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多