0

如果 makale_payments 表为空,则查询返回空。如果 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

4 回答 4

1

IFNULL是为了:

IFNULL(SUM(...), 0.0)
于 2012-04-28T23:56:22.570 回答
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
于 2012-04-29T00:00:46.763 回答
0

我猜一个简单的 WHERE 不会有伤害

WHERE SUM(`article_payment`) > 0
于 2012-04-29T00:00:25.953 回答
0

MySQL 不会为返回 null 的行返回聚合值,即使专门测试 ISNULL。ISNULL 仅用于检查列是否为空,而不是关系是否返回空。然而,我确实找到了一种(尽管非常晦涩)的方法来解决这个限制。基本前提是将两条sql语句全部union,将这两条unioned查询作为子查询进行select from。

联合查询将采用以下形式:

   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

使用上面的查询,对于关系不为空的每一行,您将获得两行,当它为空时,您将获得一行。如果您对这些行求和并分组,那么您最终应该得到您想要的值。因此,您然后创建一个查询,该查询使用上述作为表来选择并汇总聚合列:

   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。

于 2012-04-29T04:42:34.697 回答