Jakub Kulhan
Jakub Kulhan

Reputation: 1562

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?

Upvotes: 0

Views: 282

Answers (2)

mti2935
mti2935

Reputation: 12027

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 (i.e. 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 (i.e. AX's tags are subset to AY's tags).

Upvotes: 0

AgRizzo
AgRizzo

Reputation: 5271

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

Upvotes: 1

Related Questions