Mysql从2个不同的表中选择并合并结果

时间:2013-11-15 12:20:53

标签: mysql join merge

我想请教你对mysql的帮助。我想合并2个具有日期列的绝对不同的表。表格如下:

TAB1:

NAMECOLUMN   |      DATECOLUMN
------------------------------
itemname1    |      2013-01-01
itemname2    |      2013-02-02
itemname3    |      2012-04-01

TAB2:

OTHERCOLUMN  |      DATECOLUMN
------------------------------
xyz         |      2013-01-31
abcd        |      2013-01-02
efgh        |      2012-03-01

我希望按时间排序结果:

OTHERCOLUMN |      NAMECOLUMN      DATECOLUMN
---------------------------------------------
(null)      |      itemname1       2013-01-01
xyz         |      (null)          2013-01-31
abcd        |      (null)          2013-01-02
(null)      |      itemname2       2013-02-02
efgh        |      (null)          2012-03-01
(null)      |      itemname3       2012-04-01

感谢您给我指路:)

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT *
FROM (
  SELECT NULL AS othercolumn, NAMECOLUMN, datecolumn
  FROM tab1      
  UNION
  SELECT otherColumn, NULL, dateColumn
  FROM tab2
  ) a
ORDER BY datecolumn

sqlfiddle demo

编辑:

根据你的新表3,你可以这样做:

SELECT *
FROM (
  SELECT NULL as otherColumn, t1.NAMECOLUMN, t3.category,t3.type, t1.datecolumn
  FROM tab1 t1      
  INNER JOIN tab3 t3 ON t1.tab3id = t3.id
  UNION
  SELECT otherColumn, NULL,NULL,NULL, dateColumn
  FROM tab2
  ) a
ORDER BY datecolumn;

sqlfiddle demo

答案 1 :(得分:0)

你可以尝试:

SELECT namecolumn, othercolumn, t2.datecolumn
FROM Tab1 t1, Tab2 t2;

答案 2 :(得分:0)

  

选择null作为OTHERCOLUMN,NAMECOLUMN,DATECOLUMN FROM Tab1

     

UNION

     

选择OTHERCOLUMN,null为NAMECOLUMN,DATECOLUMN FROM Tab2