我有一个使用INNER JOINS的SQL查询。我需要从表offers
获得所有报价。
表offers
现在为空。但是以下查询返回一行为NULL的字段。
为什么要退货?如何解决?如果表为空,我需要返回0行。
查询:
select *, SUM(offers.price * announcement_product.amount) AS total, announcements.user_id AS creator_ann, announcements.id AS ann_id,
announcements.delivery AS deliveryAnn, announcements.payment AS
paymentAnn, SUM(announcement_product.amount) AS amount,
announcement_product.name as name_product
from `offers`
inner join `announcements` on `announcements`.`id` = `offers`.`announcement_id`
inner join `announcement_product` on `offers`.`announcement_product_id` = `announcement_product`.`id`
inner join `countries` on `countries`.`id` = `announcements`.`country`
where `offers`.`user_id` = 1 and `offers`.`status` = 1 and `offers`.`deleted_at` is null
最佳答案
您正在使用聚合函数SUM()
,但是没有任何GROUP BY
子句。
当您这样做时,您正在指示MySQL将您在SUM()
中提到的列中的所有行值加起来。即使没有要累加的行,它也会这样做。
为了获得最佳结果,您应该研究GROUP BY
函数以及如何将其与SUM()
一起使用。很难从查询中猜测出您想要什么。