Given the 4 tables, each containing items and representing one set, how to get the count of the items in each compartment required to draw a Venn diagram as shown below. The calculation should take place in the MySQL server avoiding transmission of items to the application server.
Example tables:
s1: s2: s3: s4:
+------+ +------+ +------+ +------+
| item | | item | | item | | item |
+------+ +------+ +------+ +------+
| a | | a | | a | | a |
+------+ +------+ +------+ +------+
| b | | b | | b | | c |
+------+ +------+ +------+ +------+
| c | | c | | d | | d |
+------+ +------+ +------+ +------+
| d | | e | | e | | e |
+------+ +------+ +------+ +------+
| ... | | ... | | ... | | ... |
Now, I think I would calculate some set powers. Some examples with I
corresponding to s1
, II
to s2
, III
to s3
and IV
to s4
:
If I reinterpret sx
as being a set, I would write:
|s1 ∩ s2 ∩ s3 ∩ s4|
- the white 25 in the center|(s1 ∩ s2 ∩ s4) \ s3|
- the white 15 below right in relation to the center|(s1 ∩ s4) \ (s2 ∪ s3)|
- the white 5 on the bottom|s1 \ (s2 ∪ s3 ∪ s4)|
- the dark blue 60 on the blue ground- ... till 15.
How to calculate those powers efficiently on the MySQL server? Does MySQL provide a function aiding in the calculation?
A naive approach would be running a query for 1.
SELECT count(*) FROM(
SELECT item FROM s1
INTERSECT
SELECT item FROM s2
INTERSECT
SELECT item FROM s3
INTERSECT
SELECT item FROM s4);
and another query for 2.
SELECT count(*) FROM(
SELECT item FROM s1
INTERSECT
SELECT item FROM s2
INTERSECT
SELECT item FROM s4
EXCEPT
SELECT item FROM s3);
and so on, resulting in 15 queries.