MySQL:使用Case When Then End为多个Inner Join表

时间:2012-04-23 16:57:28

标签: mysql

我有一个查询,它使用三个连接表的'Case When Then End'返回结果。它看起来像这样:

select f.filename, 
sum(case when v.rUser like '%bike%' then 1 else 0 end) as bikeUser, 
sum(case when v.rUser like '%Pedestrian%' then 1 else 0 end) as pedestrianUser, 
sum(case when d.weather like '%clear%' then 1 else 0 end) as clearWeather
from VMdata v 
inner join files f on v.id = f.id
inner join DMdata d on f.id = d.id
where f.filename in (X,Y,Z)
group by f.filename 

这样可以正常工作,每个结果行正确地给出1或0。这里要注意的是每个表只有一个特定“文件名”的条目(行)。 现在,当我尝试添加另一个内部联接时,每个“文件名”可以有多个条目(行)的表,结果会变成错误,只有最后一个'sum'显示正确的值,而其他'sums'给出错误值。第二个查询是:

select f.filename, 
sum(case when v.rUser like '%bike%' then 1 else 0 end) as bikeUser,
sum(case when v.rUser like '%Pedestrian%' then 1 else 0 end) as pedestrianUser, 
sum(case when d.weather like '%clear%' then 1 else 0 end) as clearWeather,
sum(case when m.extras like '%hat%' then 1 else 0 end) as hatExtras
from VMdata v 
inner join files f on v.id = f.id
inner join DMdata d on f.id = d.id
inner join MultiFiledata m on f.id = m.id
where f.filename in (X,Y,Z)
group by f.filename

想知道所有列的正确数据吗?

2 个答案:

答案 0 :(得分:1)

如果MultiFiledata表可以包含files表中任何相应记录的多个记录,那么您需要在单独的查询中进行聚合并将其连接回主查询。

例如(语法可能不完美;专注于概念):

select   f.filename, 
         sum(case when v.rUser like '%bike%' 
                  then 1 else 0 end) as bikeUser,
         sum(case when v.rUser like '%Pedestrian%' 
                  then 1 else 0 end) as pedestrianUser, 
         sum(case when d.weather like '%clear%' 
                  then 1 else 0 end) as clearWeather
from     VMdata v 
         inner join files f 
         on v.id = f.id
         inner join DMdata d 
         on f.id = d.id
         inner join (
             select id, 
                    sum(case when extras like '%hat%' 
                             then 1 else 0 end) as hatExtras
             from   MultiFiledata 
         ) m 
         on f.id = m.id
where    f.filename in (X,Y,Z)
group by f.filename;

答案 1 :(得分:0)

您的一对多联接导致整体行数增加,这样当您的值= 1时,您将多次添加该值。为了缓解这种情况,您可能希望使用count函数,使用它来计算不同的用户ID。类似的东西:

Count(distinct case when [logic goes here] then [user ID] else null end) as bikeuser

然后,您只计算每个用户一次而不是添加每一行。