mysql - LEFT JOIN 成为隐式连接我如何修复它?

标签 mysql subquery left-join

此查询使用一个 JOIN 而不是 LEFT 连接,但我不知道该怎么做 没有使用 cierre_mensual 表的 wheres 子句:

SELECT last_odometro.equipo, IFNULL(SUM(cierre_mensual.recorrido),0) + 
      last_odometro.recorrido AS ultimo_odometro
FROM (
    SELECT *
    FROM `cierre_mensual`
    WHERE mes < '2012-03-01'
    AND `tipo_de_recorrido`
    IN ( 1, 3 )
    GROUP BY `equipo`
    HAVING MAX( mes ) 
) AS last_odometro
LEFT JOIN 
    `cierre_mensual` ON last_odometro.`equipo` = cierre_mensual.`equipo`
WHERE 
        cierre_mensual.mes > last_odometro.mes
    AND cierre_mensual.mes < '2012-03-01'
GROUP BY `last_odometro`.`equipo`

表格字段是: id equipo mes combustible_en_tanque recorrido tipo_de_recorrido

1)我想找到 tipo_de_recorrido 是 (1,3) 的最后一个 mes(date) 2)如果存在,则将其余的 recorrido 与更大的 mes 相加

equipo  mes     combustible_en_tanque   recorrido   tipo_de_recorrido
7   2011-07-01  4   100     2
7   2011-07-01  4   100     2
7   2011-08-01  4   193900  1
7   2011-09-01  4   194000  1  <- the last row of type 1 194000
7   2011-10-01  4   100     2   +=100
7   2011-11-01  4   100     2   +=100 
7   2011-12-01  4   100     2   +=100
7   2012-01-01  7   150     2   +=150
7   2012-02-01  4   50  2       +=50

它的返回:

equipo  ultimo_odometro
   7     195150  

但是如果:

7   2011-07-01  4   100     2
7   2011-07-01  4   100     2
7   2011-08-01  4   193900  1
7   2011-09-01  4   194000  1  <- the last row of type 1 194000
no more rows whit type!=(1,2)

必须返回 194000 但连接失败。

最佳答案

您可以将条件从 WHERE 子句移动到 LEFT JOINON 子句:

LEFT
JOIN `cierre_mensual`
  ON last_odometro.`equipo` = cierre_mensual.`equipo`
 AND cierre_mensual.mes > last_odometro.mes
 AND cierre_mensual.mes < '2012-03-01'

关于mysql - LEFT JOIN 成为隐式连接我如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11477907/

相关文章:

mysql - 从 Lua 调用存储过程返回不完整的结果

php - 通过选择查询创建 RAG 状态

mysql - 如何在mysql中选择所有重复记录

postgresql - 在复杂查询上生成有序序列排名

jpa - 使用 JPA Criteria API 的 select 子句中的子查询

sql - MySQL:有效地查找列的内容是字符串开头的行

php - 错误代码 : 1093. 您无法在 FROM 子句中指定用于更新的目标表 'mm'

mysql - INNER 或 LEFT 将多个表记录连接成一行

mysql - 多个左连接

mysql - 使用 : join, 优化 MySQL 查询 where, group by, having