带sum的mysql连接查询返回null

时间:2012-04-28 23:53:02

标签: mysql join sum

如果makale_payments表为null,则查询返回null。如果在SUM(payment_total)中不存在像0.00一样,我如何设置查询以获得重新调整?

SELECT article_name,user_real_name,user_name,SUM(`article_payment`) as holding,paid
FROM makale_articles AS t1
JOIN makale_users ON (t1.article_name=makale_users.user_id) 
JOIN (SELECT user_id,SUM(`payment_total`) as paid FROM makale_payments GROUP BY user_id) AS t2 ON (t1.article_name=t2.user_id)
GROUP BY t2.user_id

4 个答案:

答案 0 :(得分:1)

这是IFNULL的用途:

IFNULL(SUM(...), 0.0)

答案 1 :(得分:1)

对于某些行,

article_payment可能是NULL。试试这个:

SELECT 
    article_name,
    user_real_name,
    user_name,
    SUM(COALESCE(`article_payment`, 0)) as holding,
    paid
FROM article_articles AS t1
JOIN article_users ON (t1.article_name=article_users.user_id) 
JOIN (
    SELECT user_id, SUM(COALESCE(`payment_total`, 0)) as paid 
    FROM article_payments 
    GROUP BY user_id
) AS t2 ON (t1.article_name=t2.user_id)
GROUP BY t2.user_id

答案 2 :(得分:0)

一个简单的地方我不会受伤

WHERE SUM(`article_payment`) > 0

答案 3 :(得分:0)

MySQL不返回返回null的行的聚合值,即使是专门测试ISNULL也是如此。 ISNULL仅检查列是否为null,而不是关系返回null。然而,我确实找到了一种(虽然非常模糊)解决这个限制的方法。基本前提是将所有两个sql语句联合起来,并使用两个联合查询作为子查询来进行选择。

联合查询的格式为:

   select column1, column2, SUM(column3) as payment from tablea, tableb where....
   union all
   select column1, column2, 0.00 as payment from tablea --notice no join, and a specified value and alias for aggregate column

使用上面的查询,对于每个关系不为null的行,您将获得两行,当它是时,您将获得一行。如果对行和分组进行求和,那么您应该得到所需的值。然后,您创建一个查询,使用上面的表作为表格进行选择并汇总聚合列:

   select column1, column2, SUM(payment) from

   (select column1, column2, SUM(column3) as payment from tablea, tableb where....
   union all
   select column1, column2, 0.00 as payment from tablea) as b
   group by column1, column2

我可能关闭了查询的语法,抱歉,我这里没有MySQL来测试。