user3666931
user3666931

Reputation: 3

MySql search for sets that are subsets of a given set

I am solving a problem with MySQL regarding subsets. I am given (a table(?) of) some Sets that need to be checked whether they are subsets of a specific set.

SELECT Subsets FROM table WHERE Subset IN(SpecificSet);

A small example could be:

SpecificSet: 
1,2,3,4,5

Subsets: 
1,2,3
4,5
4,5,6
1,2,5
1,5,6

Result:
1,2,3
4,5
1,2,5

What could be the smart way to implement structure of tables and run queries?

Upvotes: 0

Views: 151

Answers (1)

Jeff
Jeff

Reputation: 167

Would it be possible to store your sets as INTs?

If so you could use the binary and (&) to get the intersection. Each set bit would represent the number such than 2^(n-1) = bit(n)

Example:

specific set: 1,2,3,4,5 = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 = 00...11111 = 31

subsets:

1,2,3 = 7

4,5 = 24

4,5,6 = 63

intersections would be:

31 & 7 = 7

31 & 24 = 24

31 & 63 = 24

Upvotes: 1

Related Questions