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!
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on 'fname' and 'Lname' columns of the table named 'testing'.
SELECT Statement: The GROUP BY Clause in SQLA GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With