Question

I have two views and I want to retrieve their data in a single dataset. I know I have to use join but I am not getting the proper result.

View1 data:

id1 | col1 | col2 | col3 

1   | abc  | xyz | err

2   | pqr  | foo | err10

View2 data:

id2 | col1 | col2 | col4

1   | abc | xyz | tmp1

2   | xyz | rst | tmp10

3   | xyz | test | tmp5

Expected Result:

col1 | col2 | col3 | col4

abc  | xyz | err | NULL

abc  | xyz | NULL | tmp1

pqr  | foo | err10 | NULL

xyz | rst | NULL | tmp10

xyz | test | NULL | tmp5

col1 and col2 should not display twice, all the entries should come in the same column.

I am using MySQL 5.5.8

Was it helpful?

Solution

Looks like a standard union all to me:

select col1, col2, col3, NULL as col4
  from view1
 union all
select col1, col2, NULL as col3, col4
  from view2

To get the ordering from your output, you can specify an order by clause as such:

select * from (

   select col1, col2, col3, NULL as col4
     from view1
    union all
   select col1, col2, NULL as col3, col4
     from view2

) a order by col1

See also the SQLFiddle

OTHER TIPS

you need this:

SELECT 
col1, col2, col3, NULL AS col4
FROM view1
UNION 
SELECT 
col1, col2, NULL AS col3, col4
FROM view2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top