2014-07-17 92 views
1

在我的mysql查詢中,如果存在元素,我將計數它。如果產品存在,它會返回實際計數,但如果沒有產品,則返回NULL。如果值爲空,我怎麼能返回0?我發現OneTwo與此問題有關的線索。但他們都沒有幫助。防止計數()在mysql中返回「NULL」

我的查詢是

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

請幫助我...任何幫助將不勝感激。謝謝你在前進

+0

你能給你的數據結構和數據的例子嗎? –

+0

對不起。這些是大桌子。 :( – Arun

+0

好吧,請嘗試與計數(t1.id),而不是計數(*); –

回答

0

你應該將其封裝:

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 
+0

thak you for help..but it again returns null .. :(, @OscarPérez – Arun

+0

@Arun這很奇怪....你如何執行這個查詢?直接從mysql提示符? –

+0

我正在使用navicat來執行查詢,navicat和php代碼都返回null – Arun