I have one stuff in one table (A) and category of it in two others (C1,C2)
category_id coming from different table (MC).
I would like to count how many stuffs presented in particular category.
Example of live data:
table A
main_key (unique) stuff_id (non unique)
1 7
2 6
3 3
table C1
category_id main_key (it is FK for A table)
1 1
1 2
3 1
table C2
category_id main_key (it is FK for A table)
2 3
2 1
table MC
category_id category_name
1 blablbl
2 asas
3 asasa
...
relation between:
C1 and A as many to one
C2 and A as many to one
C1 or C2 and MC as many to one
In current example I would like to see final result as
stuff_qnt category_id category_name
2 1 blablbl
2 2 asas
1 3 asasa
how I can achieve it with one single query ?
my query is:
SELECT count(A.stuff_id) as stuff_qnt, MC.category_id, MC.category_name
FROM A
LEFT JOIN C1 using(main_key)
LEFT JOIN C2 using(main_key)
LEFT JOIN MC ON (C1.category_id = MC.category_id AND C2.category_id = MC.category_id)
GROUP BY C1.category_id, C2.category_id
But it shows me wrong result, what I’m doing wrong ?
You need the categories from joining A with C1 and the categories from joining A with C2, and you definitely don’t want a Cartesian product such as you’d get with LEFT OUTER JOIN, so you take the UNION of the lists of category IDs, and then aggregate and join with MC.
Output:
Here is a further test with two extra rows in A, and corresponding rows in C1 and C2. There are two queries tested, mine and the query by dkkumargoyal.
The changes made were necessary for the code to work on the test DBMS (Informix 11.70.FC6).
Results 1:
Results 2:
I think my result is correct and the other not, mainly because the alternative depends on
A.Stuff_IDbeing unique when the question stipulates that it is not unique (and the additional rows of data make it non-unique).