1

I n my mysql query, I am taking the count of elements if it exists. It returns the actual count if the product exists, but returns NULL if there is no product. How could I return 0 if the value is null? I found One, Two threads relating to this issue. But none of them helps.

My query is

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

I also tried IFNULL(count(*), 0). And it too give NULL

Please help me... any help will be appreciated. Thank you in advance

Community
  • 1
  • 1
Arun
  • 3,640
  • 7
  • 44
  • 87

1 Answers1

0

You should encapsulate it:

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
Oscar Pérez
  • 4,377
  • 1
  • 17
  • 36