我有三个表tl_log,tl_geo_countries,tl_purpose。我想在表'tl_purpose'中为每个目的获取表'tl_log'中每个国家/地区所花费的天数。 我试过下面的mysql查询
SELECT t.country_id AS countryID,t.reason_id AS reasonID,count(t.reason_id) AS
days,c.name AS country, p.purpose AS purpose
FROM `tl_log` AS t
LEFT JOIN tl_geo_countries AS c ON t.country_id=c.id
LEFT JOIN tl_purpose AS p ON t.reason_id=p.id
GROUP BY t.reason_id,t.country_id ORDER BY days DESC
但与之相伴。
我无法获得'tl_log'中每个国家/地区的计数,而这些国家/地区'tl_log'中没有该数据。任何帮助是极大的赞赏。另外,如果这个问题很难理解,请告诉我。
预期输出:
以下是这三个表格的结构
tl_log
tl_geo_countries
tl_purpose
答案 0 :(得分:1)
如果你想要所有可能的国家和目的组合,即使那些没有出现在日志表中的(这些将显示为0),你可以先做两个表的笛卡尔积(a { {1}} join)然后CROSS
加入日志表:
LEFT
如果您只想要记录表中存在的国家/地区(但仍有所有可能的原因/目的),则需要稍作修改:
SELECT
c.id AS countryID,
p.id AS reasonID,
COUNT(t.reason_id) AS days,
c.name AS country,
p.purpose AS purpose
FROM
tl_geo_countries AS c
CROSS JOIN
tl_purpose AS p
LEFT JOIN
tl_log AS t
ON t.country_id = c.id
AND t.reason_id = p.id
GROUP BY
p.id,
c.id
ORDER BY
days DESC ;
答案 1 :(得分:0)
LEFT JOIN
应替换为RIGHT JOIN