查询多对多链接 Table

Querying a Many-to-Many Linking Table

我有一个多对多关系的链接 table,其中包含字段 -

我想过滤与包含指定数量标签的笔记关联的所有标签。

例如,如果我 select 标签“Running”、“Form”和“Times”,那么我想查看所有与具有这 3 个标签的笔记关联的标签。

这个过程将被前端的用户用来细化他们正在寻找的结果,所以我需要能够用代码(node.js)生成这个SQL,标签过滤可能会发生多次。

我有下面的SQL代码,可以查询两个标签,但是有一些问题:

  1. 好像效率不高
  2. 如果需要再增加一层文件管理器,则无法通过代码轻松生成
SELECT DISTINCT idtag FROM table WHERE idnote IN (SELECT idnote FROM 
(SELECT * FROM table WHERE idnote IN (SELECT idnote FROM table WHERE idtag 
= 'Example')) as t1 where t1.idtag = 'SecondExample');

我希望就如何提高此代码的效率以及将 sql 语句变成易于代码生成的内容提出一些建议。

笛卡尔积,听起来像个数据陷阱 https://en.wikipedia.org/wiki/Cartesian_product

有什么东西可以连接这两个 table 吗? 就像我们可以加入的两者之间的共同 table 一样? 而不是 N:N
Table A 与注释 table (B) 和标签 table (C) 有共同之处 我们可以将 Table A 连接到 Table B 作为 1:N Table A 也以 1:N

加入 C

然后您可以将两个单独的事实与一个共同的 table

拼接在一起

尝试这样的事情:

; with cteTagList as 
    (select 'Example' idtag
    union select 'SecondExample'
    --...
    union select 'LastExample'
    )
select t.idnote
from table t inner join cteTabList l on l.idtag = t.idtag
group by t.idnote
having count(*) = [NUMBER_OF_SEARCH_TAGS]

在其中生成包含所有搜索标签的 CTE(通用 Table 表达式)。将其与 many-to-many 关系 table 连接起来,并且只有 select 帽子计数等于用户输入的搜索标签数量的注释,在查询中注释 [NUMBER_OF_SEARCH_TAGS]

我用你的例子 'Running','Form','Times' 作为指定的标签集。

select distinct idTag from table 
where idNote in (select idNote from table where idTag in ('Running'))
and idNote in (select idNote from table where idTag in ('Form'))
and idNote in (select idNote from table where idTag in ('Times'))