Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL left join does not work correctly

I want to left join 2 tables. So all attributes of left table should be shown in result table, no matter if it can join with other table or not.

When I do the follwing, I dont get the expected result

week_table:
 date       kw note
 ---------- -- ----
 2012-04-01  0 NULL
 2012-04-02  0 NULL

fact_table:
id number_of_application number_of_cluster number_of_jvm number_of_node number_of_was fk_wasversion fk_date    fk_domain fk_osname fk_osarch fk_osversion fk_stage
 -- --------------------- ----------------- ------------- -------------- ------------- ------------- ---------- --------- --------- --------- ------------ --------
  1                   114                 8            80             18            18 6.0           2012-04-01 domain1   Linux     sparc     2            stage1
  2                   114                 8            80             18            18 6.0           2012-04-02 domain1   Linux     sparc     2            stage1
  3                   114                 8            80             18            18 6.0           2012-04-01 domain1   AIX       sparc     2            stage1
  4                   114                 8            80             18            18 6.0           2012-04-02 domain1   Solaris   sparc     2            stage1

When I do this:

select
  w.date,
  coalesce(sum(f.number_of_was), 0)
from 
  week_table w
    left join fact_table f on (w.date = f.fk_date) 
where f.fk_osname = "AIX" 
group by w.date;

I only get :

 date       coalesce(sum(f.number_of_was), 0)
 ---------- ---------------------------------
 2012-04-01                                18

Expected:

date       coalesce(sum(f.number_of_was), 0)
---------- --------------------------------
2012-04-02                         18

Does someone know why?

Best Regards

like image 674
veote Avatar asked Jul 10 '26 13:07

veote


1 Answers

Move the criteria on the outer joined table from the WHERE clause to the ON clause:

select
  w.date,
  coalesce(sum(f.number_of_was), 0)
from 
  week_table w
    left join fact_table f on (w.date = f.fk_date and f.fk_osname = "AIX") 
group by w.date;
like image 130
Ike Walker Avatar answered Jul 14 '26 07:07

Ike Walker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!