LEFT JOIN和GROUP BY问题

时间:2017-11-08 13:23:03

标签: mysql join

很长一段时间没写MySQL,我无法理解为什么这不起作用!我写了以下内容,希望能让我看到每年的作物产量。

我有两个表,一个说明有多少种具有以下字段的植物,这称为“growseason”:

  • id
  • 用户名
  • 品种
  • 邮戳
  • 植物

我的另一个表在用户向数据库添加收获时有条目,这称为“harvest”,其中包含以下字段:

  • ID
  • 邮戳
  • 用户名
  • 各种
  • 拾取
  • 重量

我正在尝试创建一个表格,显示每株作物的年度收成,这将为我提供一个迹象,表明作物是否比上一年更好或更差。

SELECT g.Variety, 

ROUND(SUM(IF(YEAR(h.datestamp)=YEAR(CURRENT_DATE),h.picked,0)) /
IF(YEAR(g.datestamp)=YEAR(CURRENT_DATE),g.plants,0),0) As FruitPerPlantThisYear, 

ROUND(SUM(IF(YEAR(h.datestamp)=YEAR(CURRENT_DATE)-1,h.picked,0)) /
IF(YEAR(g.datestamp)=YEAR(CURRENT_DATE)-1,g.plants,0),0) As FruitPerPlantLastYear

FROM harvest h
LEFT JOIN growseason g ON h.variety = g.variety AND YEAR(h.datestamp) = YEAR(g.datestamp) AND h.username = g.username
WHERE g.username = 'Palendrone' AND picked <> '0' 
GROUP BY variety, g.datestamp

预期产出:

Variety | FruitPerPlantThisYear | FruitPerPlantLastYear
-------------------------------------------------------
Var1    |           34          |           31

Var2    |           112         |           123

Var3    |           67          |           41

实际输出:

Variety | FruitPerPlantThisYear | FruitPerPlantLastYear
-------------------------------------------------------
Var1    |           34          |            

Var2    |                       |           123

Var3    |                       |           41

我理解我的群组中的g.datestamp复制了各种名称,但如果我不添加,那么我今年或去年只会收到一个实例。花了好几个小时试图解决这个问题,我现在都是出于想法。

我愿意接受并接受帮助!也不确定我怎么能更好地构建这个......

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找条件聚合,我不知道你从gtplast获取g.datestamp的位置,因为它们不在你的表定义中。

SELECT g.Variety, 
sum(case when YEAR(h.datestamp)=YEAR(CURRENT_DATE) then h.picked else 0 end) /
sum(case when YEAR(g.datestamp)=YEAR(CURRENT_DATE) then g.plants else 0 end) as fruitPerPlantThisYear, 

sum(case when YEAR(h.datestamp)=YEAR(CURRENT_DATE) -1 then h.picked else 0 end) /
sum(case when YEAR(g.datestamp)=YEAR(CURRENT_DATE) -1 then g.plants else 0 end) as fruitPerPlantThislastYear 

FROM harvest h
LEFT JOIN growseason g ON h.variety = g.variety AND h.username = g.username
WHERE g.username = 'Palendrone' AND picked <> '0' 
GROUP BY g.variety