mysql select 查询中的意外查询结果

Unexpected query result in mysql select query

我正在尝试 运行 MySQL 查询以从 table 中获取最后的生产数量(这是用户之前添加的数量,在这种情况下为 7)称为生产,但我得到的是最高生产。这些是 tables:

_____ Production ___________
"production_id","prod_id","production_date","production_qty"
"1","40001","2020-04-15","35"
"2","40002","2019-02-08","54"
"3","40002","2020-04-08","67"
"4","40001","2020-04-02","76"
"5","40001","2020-05-08","21"
"6","40001","2020-04-29","34"
"7","40003","2020-04-03","545"
"8","40003","2020-04-18","7"
"9","40001","2020-04-25","6"
"10","40001","2020-04-25","6"
"11","40001","2020-04-25","6"
"12","40002","2020-04-13","5"
"13","40003","2020-04-01","5"
"14","40001","2020-04-17","3"
"15","40003","2020-04-04","2"
"16","40002","2020-04-11","45"
"17","40001","2020-04-02","4"
"18","40002","2020-04-01","3"
"19","40003","2020-04-17","2"
"20","40003","2020-04-29","3"

______ Products ____________
"product_id","product_name","product_unit","product_group","product_size"
"40001","tested","Gram","EVA","7/10"
"40002","testing","KG","EVA","7/10"
"40003","teste454","KG","PU","7/10"

这是我的查询:

SELECT product_id, product_unit, production_qty, SUM(production_qty) as prod_in_hand FROM 
products JOIN production ON products.product_id = production.prod_id WHERE product_id = 
40003 AND production_date < CURRENT_DATE

以上查询生成此结果:

prod_id, product_unit, production_qty, prod_in_hand
40003, KG, 545, 561

但我希望 production_qty 是“7”。 我怎样才能做到这一点? 我正在使用 XAMPP 服务器 phpMyAdmin MariaDB 服务器版本 10.3.16

我理解这是一个最大的每组 n 问题,您希望从 production 中检索 products 中的每条记录的 "last" 记录。这是使用相关子查询进行过滤的方法:

select
    ps.*,
    pn.production_date,
    pn.production_qty
from products ps
inner join production pn 
    on pn.prod_id = ps.product_id
where pn.production_date = (
    select max(pn1.production_date)
    from production pn1
    where pn1.prod_id = ps.product_id
)

如果你是运行 MySQL 8.0(或MariaDB 10.2),你也可以用row_number()来做这个:

select *
from (
    select
        ps.*,
        pn.production_date,
        pn.production_qty,
        row_number() over(partition by ps.product_id order by pn.production_date desc) rn
    from products ps
    inner join production pn 
        on pn.prod_id = ps.product_id
) t
where rn = 1