Kamil B.
Kamil B.

Reputation: 1565

Mysql select from 2 different tables and merge result

I'd like to ask you for help with mysql. I want to merge 2 absolutely different tables which has date column. Tables looks like that:

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

and I'd like to have result ordered by time:

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

Thank you for showing me way :)

Upvotes: 2

Views: 119

Answers (3)

Filipe Silva
Filipe Silva

Reputation: 21657

Try this:

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

sqlfiddle demo

EDIT:

As per your new table3, you can do:

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

Upvotes: 3

Ramesh
Ramesh

Reputation: 1942

select null as OTHERCOLUMN,NAMECOLUMN ,DATECOLUMN FROM Tab1

UNION

select OTHERCOLUMN,null as NAMECOLUMN,DATECOLUMN FROM Tab2

Upvotes: 0

Franck
Franck

Reputation: 160

Can you try :

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

?

Upvotes: 0

Related Questions