简体   繁体   中英

MySQL: Subsets and supersets of M:N relation

Let's say I have typical M:N relation table for articles and tags.

 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). Et vice versa, A2's tags are subset of A1's. A3's are neither superset, nor subset of A1's or A2's tags.

What is the most efficient way to find whether AX's tags are subset to AY's?

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. Then you could use this in another query with the EXISTS or NOT EXISTS functions

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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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