简体   繁体   English

MySQL:M:N关系的子集和超集

[英]MySQL: Subsets and supersets of M:N relation

Let's say I have typical M:N relation table for articles and tags. 假设我有用于文章和标签的典型M:​​N关系表。

 article_id | tag_id
------------+--------
 A1         | T1
 A1         | T2
 A1         | T3
 A2         | T1
 A2         | T2
 A3         | T1
 A3         | T4

In this example article A1's tags (T1, T2, T3) are superset of article A2's tags (T1, T2). 在此示例中,商品A1的标签(T1,T2,T3)是商品A2的标签(T1,T2)的超集。 Et vice versa, A2's tags are subset of A1's. 反之亦然,A2的标签是A1的子集。 A3's are neither superset, nor subset of A1's or A2's tags. A3既不是超集,也不是A1或A2的标签的子集。

What is the most efficient way to find whether AX's tags are subset to AY's? 查找AX标签是否是AY标签的子集的最有效方法是什么?

Couldn't you just run 你不能跑步吗

SELECT t1.*
FROM tbl AS t1 
LEFT JOIN tbl as t2
  ON t2.article_id ='A1'
  AND t1.tag_id = t2.tag_id
WHERE t1.article_id = 'A2'
  AND t2.article_id IS NULL;

If no records are returned then all A2's tags are in A1. 如果未返回任何记录,则所有A2的标签都在A1中。 Then you could use this in another query with the EXISTS or NOT EXISTS functions 然后,您可以在另一个具有EXISTSNOT EXISTS函数的查询中使用它

You can test whether one set is a subset of another using a query with a subquery, like so: 您可以使用带有子查询的查询来测试一组是否为另一组的子集,如下所示:

select tag_id from tablename where article_id=AX
and tag_id not in (select tag_id from tablename where article_id=AY)

If the query returns 1 or more records, then there are tags in AX which are not in AY (ie AX's tags are not subset to AY's tags). 如果查询返回1条或多条记录,则AX中有一些不在AY中的标签(即AX的标签不是AY的标签的子集)。

If the query returns 0 records, then there are no tags in AX which are not in AY (ie AX's tags are subset to AY's tags). 如果查询返回0条记录,则AX中没有不在AY中的标签(即AX的标签是AY的标签的子集)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM