在简单关联 table 上使用 mysql 中的关系除法

Using relational division in mysql on a simple associative table

我们有一个关联 table 将线程与标签连接起来。我们正在尝试找出一个查询,该查询将为我们提供与标签 ID 组合相关联的任何线程 ID。我在以下位置创建了一个 sqlfiddle:

http://sqlfiddle.com/#!9/c8ebe/3

所以 table 的结构如下:

 CREATE TABLE `threads_tags` (
  `ID_threads` bigint(20),
  `ID_tags` bigint(20)
);

一些示例数据可能如下所示:

ID_threads   ID_tags
  2             12
  4             12
  9             10
  2             21
  3             2
  2             1
  5             1
  5             21

在我们的示例中,我们将有标签 ID 的 12 和 1,我们需要一个查询 return 2 用于 ID_threads 因为这是唯一的 ID_threads 同时具有两者ID_tags = 12 和 ID_tags = 1。我们可能需要匹配的标签数量没有限制。我认为我们需要使用关系除法,我尝试使用此查询:

SELECT
    ID_threads
FROM
    threads_tags tt1
WHERE
    ID_tags IN (1,12)
GROUP BY
    ID_threads
HAVING
    count(*) = (
        SELECT
            count(*)
        FROM
            threads_tags tt2
        WHERE
            ID_threads = tt1.ID_threads
    )

虽然它似乎没有用。我考虑过使用类似于 Relational division in mysql without aggregrate functions? 处的解决方案,但在该示例中,我不确定将要输入查询的 ID_tags 列表放在哪里。我真的是关系部门类型查询的新手,所以如果您能在这里给我任何帮助,我将不胜感激。

这应该是您要查找的内容:

SELECT ID_threads FROM threads_tags
    WHERE ID_tags IN (1,12)
 GROUP BY ID_threads
 HAVING COUNT(DISTINCT ID_tags) = 2;

HAVING COUNT... 之后的数字 2 是列表中值的数量(在本例中为 2 - 1 和 12)。