[英]Problem with LEFT JOIN in MySQL
我有2张桌子
countries:
id, name
results:
id, stat, type, country, value, date
stat
可以是任何10个值和type
2的一个Country
是在该国的ID countries
表。
特定日期的结果并不包含所有国家/地区。
如何创建LEFT JOIN
以便为所有stat
- type
组合列出所有国家/地区,因此,如果一个国家/地区没有结果,则将显示0(或NULL)。
我尝试了SELECT * FROM dt_countries c LEFT JOIN results r ON c.id = r.country
作为测试,但没有显示我想要的结果。
谢谢
使用LEFT OUTER JOIN
SELECT *
FROM results r
LEFT OUTER JOIN dt_countries c
ON c.id = r.country
您没有支持这样做的表结构(或者,如果没有,则没有列出的表)。 您需要做的是以下三个表:
(仅供参考,SQL表通常以单数形式命名,即Country
, Result
, CountryResult
等。)
您列出的内容仅相当于Country
和CountryResult
表。
如果您有第三个表,则可以执行以下操作:
select
c.Name as Country,
r.Name as Result,
cr.Value as Value
from Country c
cross join Result r -- We WANT a cartesian product
left join CountryResult cr on cr.CountryId = c.CountryId and cr.ResultId = r.ResultId
select st.stat, st.type, r.date, c.name, r.value
from
(select distinct stat, type from results) st
cross join dt_countries c
left outer join results r on
c.id = r.country and r.stat = st.stat and r.type = st.type
order by st.stat, st.type, r.date, c.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.