我在查询中使用多个左连接有点麻烦。有些表与左表有一对一的关系,有些有一对多的关系。查询看起来是这样的:MySql:多个左连接给出错误的输出
Select
files.filename,
coalesce(count(distinct case
when dm_data.weather like '%clear%' then 1
end),
0) as clear,
coalesce(count(distinct case
when dm_data.weather like '%lightRain%' then 1
end),
0) as lightRain,
coalesce(count(case
when kc_data.type like '%bicycle%' then 1
end),
0) as bicycle,
coalesce(count(case
when kc_data.type like '%bus%' then 1
end),
0) as bus,
coalesce(count(case
when kpo_data.movement like '%walking%' then 1
end),
0) as walking,
coalesce(count(case
when kpo_data.type like '%pedestrian%' then 1
end),
0) as pedestrian
from
files
left join
dm_data ON dm_data.id = files.id
left join
kc_data ON kc_data.id = files.id
left join
kpo_data ON kpo_data.id = files.id
where
files.filename in (X, Y, Z, ........)
group by files.filename;
这里,dm_data表中有“文件”表一比一的关系(这就是为什么我使用“独特”),而kc_data和kpo_data数据具有单与“文件”表的多对多关系。 (对于一个files.id,kc_data和kpo_data可以有10到20行)。这个查询工作正常。
问题出现时,我添加另一个一对多表pd_markings(它可以有100行对一个files.id)的另一个左连接。
Select
files.filename,
coalesce(count(distinct case
when dm_data.weather like '%clear%' then 1
end),
0) as clear,
coalesce(count(distinct case
when dm_data.weather like '%lightRain%' then 1
end),
0) as lightRain,
coalesce(count(case
when kc_data.type like '%bicycle%' then 1
end),
0) as bicycle,
coalesce(count(case
when kc_data.type like '%bus%' then 1
end),
0) as bus,
coalesce(count(case
when kpo_data.movement like '%walking%' then 1
end),
0) as walking,
coalesce(count(case
when kpo_data.type like '%pedestrian%' then 1
end),
0) as pedestrian,
**coalesce(count(case
when pd_markings.movement like '%walking%' then 1
end),
0) as walking**
from
files
left join
dm_data ON dm_data.id = files.id
left join
kc_data ON kc_data.id = files.id
left join
kpo_data ON kpo_data.id = files.id
left join
**kpo_data ON pd_markings.id = files.id**
where
files.filename in (X, Y, Z, ........)
group by files.filename;
现在所有的值都成为对方的倍数。有任何想法吗???
请注意,前两列返回1或0值。这实际上是理想的结果,因为一对一关系表只有1或0行对任何文件.id,所以如果我不使用'差异',那么结果值是错误的(我猜是因为其他表格返回的是同一个file.id中的一行以上)不幸的是,不幸的是,我的表没有自己唯一的ID列,除了'文件'表。
感谢您的好解释。 – sunsa428
你现在的查询如何?你能一点一点解决吗? :-) –
感谢您的好解释。 不,MySql不支持CTE风格的查询。所以我会和其他建议一起去。其他人也在其他帖子中提出了相同的解决方案,但我试图避免使用这些“子查询”左连接,因为连接表本身包含大量的数据,我认为这些数据可能会减慢查询执行速度。但现在看来我现在没有其他选择了。 另一件事,我们将如何在这种情况下使用“汇总”? – sunsa428