MySQL: Is it possible to JOIN the GROUP-BY'd results to two SELECTs?

join, mysql, sql

Solution

This works

select * from (
    (select 1 a,2 b,3 c) t1 left join (select null a,2 b,5 c) t2 on (t1.b=t2.b)
);

Alternatively,

select * from (
    (select 1 a,2 b,3 c) t1 left join (select null a,2 b,5 c) t2 using (b)
);

Both result in

+---+---+---+------+---+---+
| a | b | c | a    | b | c |
+---+---+---+------+---+---+
| 1 | 2 | 3 | NULL | 2 | 5 |
+---+---+---+------+---+---+
1 row in set (0.00 sec)

Problem

I have two separate SELECT statements which are both GROUP-BY'd separately e.g.: ``` SELECT x, y, z FROM a GROUP BY x SELECT x, n, o FROM b GROUP BY x ``` I would very much like to JOIN these two SELECTs together to combine their columns, such as: ``` SELECT x as x1, y, z FROM a GROUP BY x LEFT JOIN ( SELECT x as x2, n, o FROM b GROUP BY x) ON x1=x2; ``` Is this possible? I ask because MySQL is complaining You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN SELECT x as x2 If this is possible, any thoughts on what's wrong with my syntax? Thanks very much!

Original source