具有不匹配行的笛卡尔连接

时间:2019-04-22 19:23:48

标签: mysql join left-join

LEFT连接不匹配的情况下,我的查询无法正常工作。我认为这与笛卡尔联接有关。这是一个有效的查询:

select i.id, z.WeekNum, 0, count(s.id) from my156rowtable as i
left JOIN (select YEARWEEK( @startDate ) WeekNum, @startDate := date_add( @startDate, interval 1 week ) EndOfWeek
from 
(select @startDate := '2016-04-20') sqlv,
my156rowtable
limit 156 ) z
on 1=1
where i.id = 2 and s.id = 0
group by z.WeekNum, s.id

哪个带回来:

|             2 |  201836 | 0 |        1 |
|             2 |  201837 | 0 |        1 |
|             2 |  201838 | 0 |        1 |
|             2 |  201839 | 0 |        1 |
|             2 |  201840 | 0 |        1 |
|             2 |  201841 | 0 |        1 |

但是添加了stats_to_my156rowtable后,我缺少了行201838201839

select i.id, z.WeekNum, 0, count(s.id) from my156rowtable as i
left JOIN (select YEARWEEK( @startDate ) WeekNum, @startDate := date_add( @startDate, interval 1 week ) EndOfWeek
from 
(select @startDate := '2016-04-20') sqlv,
my156rowtable
limit 156 ) z
on 1=1
left join stats_to_my156rowtable as s
on i.id = s.sid and z.WeekNum = YearWeek(s.date)
where i.id = 2 and s.id = 0
group by z.WeekNum, s.id

返回:

|             2 |  201836 | 0 |                  8 |
|             2 |  201837 | 0 |                 14 |
|             2 |  201840 | 0 |                  9 |

如果没有匹配项,我希望count0。我以为以后可以用casecoalesce来做到这一点,但没有回报,我运气不高。

1 个答案:

答案 0 :(得分:1)

您在WHERE子句右表中的条件将您的LEFT JOIN变成INNER JOIN。基本上,它会过滤掉id = 0的行,包括NULL行。将条件移至ON子句可能会解决您的问题。

select i.id, z.WeekNum, 0, count(s.id) 
from my156rowtable as i
left JOIN (
    select YEARWEEK( @startDate ) WeekNum, @startDate := date_add( @startDate, interval 1 week ) EndOfWeek
    from (
        select @startDate := '2016-04-20'
    ) sqlv, my156rowtable
    limit 156 
) z on 1=1
left join stats_to_my156rowtable as s on i.id = s.sid and z.WeekNum = YearWeek(s.date) AND s.id = 0
where i.id = 2
group by z.WeekNum, s.id