我在查詢中使用多個左連接有點麻煩。有些表與左表有一對一的關係,有些有一對多的關係。查詢看起來是這樣的: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