MySQL : Select the rows having the max value for one field and keep correct values for joining tables

标签 mysql sql symfony join doctrine-orm

我知道有很多与此相关的问题已经得到解答,但我花了几天时间来调整答案以适应我的案例,但我无法使其发挥作用。所以请善意地帮助我。

我执行此查询:

SELECT
    a.id,
    a.commit,
    b.id,
    c.value

FROM TableA a

INNER JOIN TableC c ON c.id_a = a.id
INNER JOIN TableB ON c.id_b = b.id
INNER JOIN TableD d ON a.id_d = d.id

WHERE a.commit <= 9000 AND a.id_s = 10 AND d.id_f = 1

ORDER BY b.custom_order, a.commit ASC

下面是该查询的结果。我只想获取每个 b.id 具有最大提交的行:

a.id | a.commit | b.id | c.value
--------------------------------
257  | 4000     | 11   | 33
258  | 6000     | 11   | 34
259  | 8000     | 11   | 35
257  | 4000     | 1    | 40
258  | 6000     | 1    | 40
259  | 8000     | 1    | 40
257  | 4000     | 2    | 40
258  | 6000     | 2    | 40
259  | 8000     | 2    | 40
257  | 4000     | 3    | 15
258  | 6000     | 3    | 25
259  | 8000     | 3    | 25

所以,我想要所有 commit = 8000 的行:

a.id | a.commit | b.id | c.value
--------------------------------
259  | 8000     | 11   | 35
259  | 8000     | 1    | 40
259  | 8000     | 2    | 40
259  | 8000     | 3    | 25

我在下面找到了这个解决方案,但我无法将其与 Symfony 3.4 和 Doctrine 一起使用,因为 Doctrine 无法在子查询上执行内部联接...

SELECT
    a1.id,
    a1.commit,
    b1.id,
    c1.value

FROM TableA a1

INNER JOIN TableC c1 ON c1.id_a = a1.id
INNER JOIN TableB ON c1.id_b = b1.id
INNER JOIN TableD d1 ON a1.id_d = d1.id

INNER JOIN(
    SELECT
        b.id,
        MAX(a.commit) max_commit

    FROM TableA a

    INNER JOIN TableC c ON c.id_a = a.id
    INNER JOIN TableB ON c.id_b = b.id
    INNER JOIN TableD d ON a.id_d = d.id

    WHERE a.id_s = 10 AND a.commit <= 9000 AND d.id_f = 1

    GROUP BY b.id

) results ON b1.id = results.id AND a1.commit = results.max_commit

WHERE a1.id_s = 10

ORDER BY b1.custom_order ASC

最佳答案

我不了解 Doctrine,但您可以使用 ROW_NUMBER() 窗口函数来过滤掉您不需要的行。例如:

SELECT
  a_id,
  commit,
  b_id,
  value
from (
  SELECT
    a.id as "a_id",
    a.commit,
    b.id as "b_id",
    c.value,
    b.custom_order,
    row_number() over(PARTITION BY b.id ORDER BY a.commit DESC) as rn
  FROM TableA a
  INNER JOIN TableC c ON c.id_a = a.id
  INNER JOIN TableB ON c.id_b = b.id
  INNER JOIN TableD d ON a.id_d = d.id
  WHERE a.commit <= 9000 AND a.id_s = 10 AND d.id_f = 1
) x
ORDER BY custom_order, commit ASC
WHERE rn = 1

关于MySQL : Select the rows having the max value for one field and keep correct values for joining tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58378081/

相关文章:

php - Symfony DateTimeType 作为单个文本小部件格式不正确

php - 使用 Symfony 2 Finder 组件获取子目录

mysql - 将 LZW 编码数据保存到 mySQL 数据库中

mysql - 创建表时分区语法错误: MySQL

mysql - 从 InnoDB 中删除行非常慢

mysql - 如何在 MySQL 中执行复杂的范围查询

javascript - 如何在 bundle 之间共享 CSS 和 JS

php - 如何在表格中显示搜索结果,同时将其导出为 csv 文件

MYSQL连接3个表并计算累计百分比

mysql用另一个表的数据更新一个表