2015-02-24 213 views
1

簡單的問題,我不能得到我的頭。 我只想將兩個沒有共同數據的表並列在一起。mysql並排查詢結果

table1 table2 -> result 
a b  e f   a b e f 
c d  g h   c d g h 
      i j   \n \n i j 

回答

0

你可以做到這一點使用RIGHT JOIN並分配一個ID,每個表的使用ROW_NUMBER來。看到我的查詢如下:

SELECT A.column1,A.column2,B.column1,B.column2 FROM 
    (SELECT 
     @row_number1:[email protected]_number1+1 AS RowNumber1, 
     column1, 
     column2 
    FROM Table1, (SELECT @row_number1:=0)AS x ORDER BY column1) AS A 
    RIGHT JOIN 
    (SELECT 
     @row_number2:[email protected]_number2+1 AS RowNumber2, 
     column1, 
     column2 
    FROM Table2, (SELECT @row_number2:=0)AS y ORDER BY column1) AS B 
    ON A.RowNumber1=B.RowNumber2 
+0

謝謝這工作得很好!我不得不將內部連接更改爲正確連接,因爲它們有不同的長度,但是那樣起作用。比我想象的要複雜一點。 – ash 2015-02-24 00:31:05

0

SQL表本質上是無序的,所以排序行的關鍵是可取的。您可以使用變量創建一個。

您的表格具有不同的行數。這意味着full outer join是可取的,但這在MySQL中不可用。所以,你可以做你想做採用聚集和union all什麼:

select max(col1) as col1, max(col2) as col2, max(col3) as col3, max(col4) as col4 
from ((select col1, col2, null as col3, null as col4, @rn1 := @rn1 + 1 as rn 
     from table1 cross join (select @rn1 := 0) vars 
    ) union all 
     (select null, null, col3, col4, @rn2 := @rn2 + 1 as rn 
     from table2 cross join (select @rn2 := 0) vars 
    ) 
    ) tt 
group by rn