如何检查mysql中是否存在某一组外键


How to check if there exists a certain set of foreign keys in mysql?

在mysql中,我有一个线程表和一个线程用户表,每个线程用户都有自己的id和线程表的外键。现在给定一组用户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,而不是或多或少的人。

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

感谢

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

SELECT thread_id
FROM thread_user
WHERE id IN (111,222)
GROUP BY thread_id
HAVING COUNT(id) = 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可以是逗号分隔的值