MySQL左连接无法正常工作

时间:2012-04-02 13:07:43

标签: mysql sql left-join

我想离开加入2个表。 所以左表的所有属性都应该显示在结果表中,无论它是否可以与其他表连接。

当我做下文时,我没有得到预期的结果

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

当我这样做时:

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;

我只得到:

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

预期:

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

有人知道为什么吗?

最好的问候

3 个答案:

答案 0 :(得分:11)

将外连接表上的条件从WHERE子句移动到ON子句:

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;

答案 1 :(得分:0)

where f.fk_osname = "AIX"

我猜这个osname只有一条记录?

答案 2 :(得分:0)

因为where f.fk_osname = "AIX"

如果右侧表中不存在数据,则为NULL,并且您要求仅检索fk_name为“AIX”的行

你可以WHERE (f.fk_osname = "AIX" OR f.fk_osname IS NULL)

相关问题