I have two tables containing three columns containing the same types of information(id, attributes, and amounts). I would like to combine them in a union and join that union with another table containing a list of id’s to filter them, then sum common attributes.
table_a table_b table_ids
id attr amount id attr amount uid a_id
1 'atr1' 10 1 'atr2' 4 'id1' 1
1 'atr2' 5 2 'atr3' 2 'id2' 2
2 'atr3' 7 2 'atr1' 11
3 'atr1' 8
I tried
SELECT table_ids.uid, t.attr, SUM(t.amount)
FROM table_ids
JOIN (SELECT CONCAT('a', id) AS comb_id, attr, amount FROM table_a
UNION ALL
SELECT CONCAT('b', id) AS comb_id, attr, amount FROM table_b
) t
ON CONCAT('a', table_ids.a_id) = t.comb_id
GROUP BY t.attr
but am only getting the attribute for last matching a_id and the number of matching rows times the last matching row amount for the sum.
(There will be another table with more id’s filtering table_b attributes but I haven’t even gotten one filtering table to work yet.)
Hard to be 100% sure what you are aiming for but something like this may fit the bill
Have of course assumed that table_b will join id onto table_ids.b_id, change it as required.