【问题标题】:How to check if there exists a certain set of foreign keys in mysql?如何检查mysql中是否存在某组外键?
【发布时间】:2015-02-18 14:29:20
【问题描述】:

在mysql中,我有一个threads表和一个threadusers表,每个threaduser都有自己的id和thread表的外键。现在给定一组用户 id,我想看看是否存在一个线程,其中的用户正是这些 id。没有更多或更少的人参与。我有这段代码,给定 2 个用户 ID,它似乎可以工作:

    $query = "SELECT th.id
              FROM (
                 SELECT th.id
                 FROM thread th
                 JOIN thread_user tu ON th.id=tu.thread_id AND (tu.user_id={$user_id} OR tu.user_id={$target_id})
                 GROUP BY th.id
                 HAVING count(tu.id)=2
              ) th
              JOIN thread_user tu ON th.id=tu.thread_id
              GROUP BY th.id
              HAVING count(tu.id)=2";

内部子查询获取用户同时包含给定 id 的所有线程。然后我将它与每个线程的所有用户一起加入,并将它们分组并再次按 2 过滤。结果应该是与给定 id 完全相同的用户的线程,没有更多或更少的人。

这似乎是多余的,有没有更好的方法?

谢谢

【问题讨论】:

    标签: php mysql join


    【解决方案1】:

    如果我正确理解了您的表结构,您应该可以通过查询链接表thread_user 来做到这一点。像这样

    SELECT thread_id
    FROM thread_user
    WHERE id IN (111,222)
    GROUP BY thread_id
    HAVING COUNT(id) = 2;
    

    【讨论】:

    • 这行不通,因为假设 thread_user 中有其他行具有相同的 thread_id 和不同的 id,那么这个查询仍然会返回那个 thread_id,而我不希望它返回那个.这是因为当前 thread_id 存在的外键集应该正好是 (111,222),不应该有或更少。
    • 你真的试过了吗?
    【解决方案2】:
    Select th.id, count (th.id) 
    from thread th 
      inner join thread_user tu on th.id = tu.thread_id 
    where tu.user_id in ({$user_id}) 
       OR tu.user_id in ({$target_id}) 
    group by (th.id) 
    having count (th.id) >= 2
    

    内连接只选择两个表中具有匹配 id 的记录。用于搜索集合 $user_id 可以是逗号分隔值

    【讨论】:

    • 这只会获取至少拥有 2 个给定用户之一的线程。我想要同时拥有这两个人的线程(不多/少)。
    • 尝试使用 group by 并拥有
    • 这个效果一样。
    猜你喜欢
    • 2021-11-11
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    相关资源
    最近更新 更多