Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

join

mysql

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!

like image 589
DarkSquid Avatar asked Jun 17 '09 05:06

DarkSquid


People also ask

Can we use GROUP BY two times?

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'.

Can you GROUP BY 2 things in SQL?

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.


1 Answers

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)
like image 173
Vinko Vrsalovic Avatar answered Nov 15 '22 08:11

Vinko Vrsalovic