tags:

views:

62

answers:

2

I want to create a view from the following two tables:

Entry:
entry_id
entry_date
entry_amount
user_id

Forecast:
forecast_id
forecast_date
forecast_amount
user_id

Now I want to have a view which combines each entry with its forecast (same user_id and same date). This is fine, but I have a problem with those rows, which have a forecast and no entry, or vice versa.

I would like to still have all entries with no forecasts as well in the database. They should show up with a null values in the forecast fields. And the same for forecasts without entries.

Thx, Martin

A: 

What have you tried?

A full outer join would do that for you. You can simulate one with two outer joins and a union all:

select
   e.entry_id, e.entry_date, e.entry_amount, e.user_id,
   f.forecast_id, f.forecast_date, f.forecast_amount, f.user_id
from
   Entry e
   left outer join Forecast f on f.user_id = e.user_id and f.forecast_date = e.entry_date
union all
select
   e.entry_id, e.entry_date, e.entry_amount, e.user_id,
   f.forecast_id, f.forecast_date, f.forecast_amount, f.user_id
from
   Entry e
   right outer join Forecast f on f.user_id = e.user_id and f.forecast_date = e.entry_date
where
   e.entry_id is null
Guffa
+1 Just add the date comparison
Roee Adler
I think this command is not available in mysql.
Binoj Antony
SELECT e.entry_id, e.user_id, e.entry__date, e.entry_amount, f.user_id, f.forecast_period_end, f.forecast_id, f.forecast_amountFROM Entry e FULL OUTER JOIN Forecast f ON e.user_id = f.user_id AND e.entry_date = f.forecast_period_endGives me an SQL error. I do not know why...
Martin
I changed the full outer join to a simulated full outer join. More info: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
Guffa
+2  A: 

This (FULL OUTER JOIN) command is not available on MySql you will need to use UNION to achieve this as given below

SELECT E.*, F.*
 FROM Entry E
 LEFT JOIN Forecast F ON E.user_id = F.user_id AND E.entry_date = F.forecast_date
UNION ALL
SELECT E.*, F.*
 FROM Forecast F 
 LEFT JOIN Entry E ON E.user_id = F.user_id AND E.entry_date = F.forecast_date
Binoj Antony
Thanks - interesting that mysql does not have FULL OUTER JOINsworks great
Martin
Using union removes duplicates. There might not be any in this case, but there isn't anything in the question that specifically excludes that. The solution to this is to use a union all instead, see my answer.
Guffa
Oh yes, you are right, corrected it.
Binoj Antony