期望此查询不会输出 0 值,但它会

expected that this query will not output 0 values, but it does

我预计此查询不会输出 0 值,但确实如此。我认为 and (...) > 0 不会输出 0 值。那么如何防止输出 0 值呢?

select lot.*, sum(movement.quantity) as value 
from lot
left join lot_movement as movement on lot.id = movement.lot_id
where lot.item_id = 8 and movement.storage_id = 3
and (select sum(lot_movement.quantity) 
    from lot_movement 
    where lot_movement.lot_id = lot.id
    ) > 0
group by lot.id;

我试图添加 and sum(lot_movement.quantity) \> 0,但这给出了错误 invalid use of group function

lots in database

lot_movements in database

output with 0 values

我明白了

and (select sum(lot_movement.quantity)
    from lot_movement
    where lot_movement.lot_id = lot.id
    group by lot_movement.lot_id) > 0

是多余的。不影响结果。

您的查询没有给出预期的结果,因为您在 where 子句中按 lot.item_id = 8 and movement.storage_id = 3 进行过滤,但您没有在子选择中应用相同的过滤。

我不太确定您要实现的目标,但我怀疑添加 having 子句而不是子选择可以解决您的问题:

select lot.id, sum(movement.quantity) as value 
from lot
left join lot_movement as movement on lot.id = movement.lot_id
where lot.item_id = 8 and movement.storage_id = 3
group by lot.id
having sum(movement.quantity) > 0