2009-06-17 60 views
6

我有兩個單獨的SELECT語句它們都是GROUP-BY'd分別例如:MySQL的:是否有可能加入該羣,BY'd結果兩個選擇α

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

如果這是可能的,任何想法上有什麼錯我的語法?

非常感謝!

回答

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) 
+0

正是我想要的 - 感謝! – DarkSquid 2009-06-17 05:59:09

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; 
    
+0

我認爲(2)是什麼,他要尋找的。 – 2009-06-17 05:20:38

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;

相關問題