如何在MySQL 5.5中执行IFNULL(count(*),0)

时间:2015-12-23 17:02:33

标签: mysql sql

我试图做一个IFNULL(计数(),0)或IF(计数()> 0,计数(*),0), 但它不起作用,我的行“计数器”显示“NULL”而不是0:/

这是我的问题:

SELECT IF(fc.counter > 0, fc.counter, 0) counter, b.*, fc.* FROM client_branche cb INNER JOIN branche b On b.id = cb.branche_id LEFT OUTER JOIN (   

    SELECT IFNULL(count(*),0) as counter, ctn_b.branche_id as b_id
    FROM `historique` h 
    INNER JOIN contenu_branche ctn_b ON ctn_b.contenu_id = h.contenu_id 
    INNER JOIN utilisateur u ON u.id = h.utilisateur_id 
    WHERE h.h_fini = 1 AND ( u.client_id = 1 OR u.client_id = 0 ) AND h.h_dateheure BETWEEN '2015-12-24' AND '2015-12-30'
    group by ctn_b.`branche_id`) 
fc ON fc.b_id = cb.branche_id WHERE cb.client_id = 1

所以我试着这样做:

{{1}}

Annnnd我失败了。我希望有人会帮助我。非常感谢,对不起我的英语不好,这不是我的母语:)

3 个答案:

答案 0 :(得分:0)

问题可能是select中有多个列具有相同的名称 - counter。解决此问题的最佳方法是不在查询中使用*,而是列出所需的列。也许更简单的方法是重命名列:

SELECT (CASE WHEN fc.counter > 0 THEN fc.counter ELSE 0 END) as fc_counter,
       b.*, fc.*
FROM client_branche cb INNER JOIN
     branche b
     On b.id = cb.branche_id LEFT OUTER JOIN
     (SELECT count(*) as counter, ctn_b.branche_id as b_id
      FROM `historique` h INNER JOIN
            contenu_branche ctn_b
            ON ctn_b.contenu_id = h.contenu_id INNER JOIN
            utilisateur u
            ON u.id = h.utilisateur_id 
      WHERE h.h_fini = 1 AND
            u.client_id IN (0, 1) AND
            h.h_dateheure BETWEEN '2015-12-24' AND '2015-12-30'
      GROUP BY ctn_b.branche_id
     ) fc
     ON fc.b_id = cb.branche_id
WHERE cb.client_id = 1;

我还做了一些其他小的更改,例如使用IN代替ORCASE(ANSI标准)而不是IF()

注意:如果counter永远不会消极,那么编写逻辑的最通俗方式是COALESCE(counter, 0),而不是CASEIF()

答案 1 :(得分:0)

它会起作用。您在子查询和主查询中使用计数器别名。所以试试吧

   SELECT IF(fc.cou > 0, fc.cou, 0) counter, b., fc.FROM client_branche cb INNER JOIN branche b On b.id = cb.branche_id LEFT OUTER JOIN ( SELECT IFNULL(count(*),0) as cou, ctn_b.branche_id as b_id FROM historiqueh INNER JOIN contenu_branche ctn_b ON ctn_b.contenu_id = h.contenu_id INNER JOIN utilisateur u ON u.id = h.utilisateur_id WHERE h.h_fini = 1 AND ( u.client_id = 1 OR u.client_id = 0 ) AND h.h_dateheure BETWEEN '2015-12-24' AND '2015-12-30' group by ctn_b.branche_id) fc ON fc.b_id = cb.branche_id WHERE cb.client_id = 1

答案 2 :(得分:0)

外部查询需要IFNULL(由于LEFT JOIN),如下所示:

count(*)

它实际上是一个" no op"在内部查询上,因为Response.Redirect("Page2.aspx", false);永远不会为空。