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

7
  • Can you give example with your data structure and data? Commented Jul 17, 2014 at 9:48
  • sorry..these are large tables. :( Commented Jul 17, 2014 at 9:54
  • Ok please try with count(t1.id) instead of count(*); Commented Jul 17, 2014 at 10:02
  • @CharveeShah : already tried and it gives null. I also tried if(count(*) = NULL,0,count(*)). This works fine if there is count > 0. Otherwise again NULL Commented Jul 17, 2014 at 10:06
  • Have you tried COALESCE() function of mysql. It does same as IFNULL. Commented Jul 17, 2014 at 10:13

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

7 Comments

thak you for help..but it again returns null.. :(, @Oscar Pérez
@Arun It is strange.... how are you executing this query? Directly from the mysql prompt?
I am using navicat for execute the query. Both navicat and php code returns null
Just to get sure: are you 100% sure that PHP return NULL? Remember that in PHP 0==NULL... You should use ===
yeah.. I checked it at the sql section of my server too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.