SQL 从一个 table 分组,从另一个分组

SQL group by from one table and max from another

我有 3 个 tables abbcdc。现在我想根据 ab table 中的 a_idc table 中的 select max date 进行分组。这是我到目前为止尝试过的:

select ab.a_id, bcd.d_id, c.val, max(c.date) as date
from tableab ab, tablebcd bcd, tablec c
where ab.b_id = bcd.b_id
and bcd.c_id = c.c_id
group by ab.a_id

它的工作没有错误,但没有给出正确的结果。我知道的不多 SQL 所以我可能遗漏了一些简单的东西。感谢您的帮助!

从您现有的查询开始,straight-forward 方法是 row_number()(仅在 MySQL 8.0 中可用)。

select * 
from (
    select 
        ab.a_id, 
        bcd.d_id, 
        c.val, 
        row_number() over(partition by ab.a_id order by c.date desc) as rn
    from tableab ab
    iner join tablebcd bcd on  ab.b_id = bcd.b_id
    inner join tablec c on bcd.c_id = c.c_id
) t
where rn = 1 

row_number() 通过降序 date 对具有相同 a_id 的记录进行排名 - 然后您可以使用此信息来过滤 table.

请注意,我重写了查询以使用标准的显式连接而不是 old-school、隐式连接(在 from 子句中使用逗号):不应使用几十年前的这种语法在新代码中。