阻止计数()返回";空";在mysql中

阻止计数()返回";空";在mysql中,mysql,count,null,Mysql,Count,Null,在我的mysql查询中,如果存在,我将计算元素的数量。如果产品存在,则返回实际计数;如果没有产品,则返回NULL。如果值为null,如何返回0?我发现,与这个问题相关的线程。但它们都没有帮助 我的问题是 SELECT COUNT(*) AS num FROM table1 AS t1 JOIN table2 AS t2 ON t2.id = t1.id_fk JOIN table3 AS t3 ON t3.id = t2.t3_id_fk JOIN table4 AS t4 ON

在我的mysql查询中,如果存在,我将计算元素的数量。如果产品存在,则返回实际计数;如果没有产品,则返回
NULL
。如果值为null,如何返回
0
?我发现,与这个问题相关的线程。但它们都没有帮助

我的问题是

SELECT
    COUNT(*) AS num
FROM
    table1 AS t1
JOIN table2 AS t2 ON t2.id = t1.id_fk
JOIN table3 AS t3 ON t3.id = t2.t3_id_fk
JOIN table4 AS t4 ON t4.id = t2.t4_id_fk
JOIN table 5 AS t5 ON t5.t2_id_fk = t2_id
WHERE pd.product_url = 'sample_product'
AND mcd.main_category_url = 'sample_category'
AND scd.sub_category_url = 'sample_sub_category'
AND mpd.merchant_prod_status = 'active'
AND pd.product_status = 'active'
AND mcd.main_category_status = 'active'
AND scd.sub_category_status = 'active'
GROUP BY t1.id
我还尝试了
IFNULL(count(*),0)
。它也会给出
NULL


请帮帮我。。。任何帮助都将不胜感激。提前谢谢你

你应该把它封装起来:

SELECT IFNULL(num,0)
  FROM ( SELECT COUNT(*) AS num
           FROM table1 AS t1
           JOIN table2 AS t2 ON t2.id = t1.id_fk
           JOIN table3 AS t3 ON t3.id = t2.t3_id_fk
           JOIN table4 AS t4 ON t4.id = t2.t4_id_fk
           JOIN table 5 AS t5 ON t5.t2_id_fk = t2_id
          WHERE pd.product_url = 'sample_product'
            AND mcd.main_category_url = 'sample_category'
            AND scd.sub_category_url = 'sample_sub_category'
            AND mpd.merchant_prod_status = 'active'
            AND pd.product_status = 'active'
            AND mcd.main_category_status = 'active'
            AND scd.sub_category_status = 'active'
       GROUP BY t1.id
      ) s

thak you for help..但它再次返回null..:(,@Oscar Pérez@Arun奇怪的是…你是如何执行这个查询的?直接从mysql提示符?我正在使用navicat执行查询。navicat和php代码都返回NULL只是为了确定:你100%确定php返回
NULL
?记住在php
0==NULL
…你应该使用
==
是的..我检查一下我也在我的服务器的sql部分使用它。你能举例说明你的数据结构和数据吗?对不起。这些是大表。:(好的,请尝试使用count(t1.id)而不是count(*);@charveesah:已经尝试过了,它给出了null。我还尝试了
如果(count(*)=null,0,count(*)
。如果count>0,则可以正常工作。否则,请再次尝试mysql的COALESCE()函数。该函数的作用与IFNULL相同。