MySQL:是否可以将GROUP-BY的结果加入两个SELECT?

时间:2009-06-17 05:06:56

标签: sql mysql join

我有两个单独的SELECT语句,它们分别是GROUP-BY,例如:

SELECT x, y, z FROM a GROUP BY x
SELECT x, n, o FROM b GROUP BY x

我非常希望将这两个SELECT连接在一起以组合它们的列,例如:

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;

这可能吗?我问,因为MySQL在抱怨

  

您的SQL语法有错误;   检查对应的手册   您的MySQL服务器版本   正确的语法在'LEFT JOIN附近使用   选择       x为x2

如果可以的话,对我的语法有什么问题的想法?

非常感谢!

3 个答案:

答案 0 :(得分:5)

这有效

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)
);

可替换地,

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

两者都会导致

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

答案 1 :(得分:4)

有几种方法可以实现这一目标:

  1. 最佳:在分组之前加入表格如下:
    SELECT a.x, y, z, n, o
      FROM a INNER JOIN b ON a.x = b.x
     GROUP BY a.x, b.x;
    
  2. 从两个查询中选择子查询,如下所示:
    SELECT *
    FROM       (SELECT x, y, z FROM a GROUP BY x) AS a
    INNER JOIN (SELECT x, n, o FROM b GROUP BY x) AS b
            ON a.x = b.x;
    

答案 2 :(得分:1)

您也可以使用此查询:
SELECT a.x, a.y, a.z, b.x, b.o, b.n FROM a, (SELECT x, n, o FROM b GROUP BY x) as b WHERE a.x = b.x GROUP BY a.x;