我的mysql查询,如果元素存在,我会计算元素的数量。如果产品存在,它返回实际计数,但如果没有产品,则返回NULL
。如果值为null,我怎么能返回0
?我找到了与此问题相关的One,Two个主题。但它们都没有帮助。
我的查询是
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)
你应该封装它:
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