2013-04-30 68 views
0

如何設置現場most_popular爲0;如果其計數爲null SELECT語句的MySQL如果計數爲null,則使零

我試過IFNULL(SELECT COUNT(*)內的select語句。 ..),0)作爲most_popular,但它不會工作,我嘗試 COALESCE(SELECT COUNT(*)......,0)作爲most_popular

$stmt = $db->prepare("SELECT *,   
    i.medium_image, i.width, i.height, 
    (SELECT COUNT(*) FROM order_details od WHERE od.product_id = p.product_id) as most_popular 

    FROM products p 
     INNER JOIN product_images i on i.product_id = p.product_id  
    WHERE p.department_id=:department_id AND p.is_active=1 
    $orderby   
    LIMIT :limit OFFSET :offset"); 
+0

'SELECT COUNT(*)...'永遠不會產生NULL。嘗試['IF(bool,val_if_true,val_if_false)'](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if)表達式。 – BlitZ 2013-04-30 03:27:49

+0

你可以給我舉例與我有IF(bool,val1,val2)語句的代碼 – ONYX 2013-04-30 03:28:34

回答

3

試試這個,

SELECT *, 
     i.medium_image, 
     i.width, 
     i.height, 
     COALESCE(s.totalCount, 0) most_popular 
FROM products p 
     INNER JOIN product_images i 
      ON i.product_id = p.product_id 
     LEFT JOIN 
     (
      SELECT product_id, Count(*) totalCount 
      FROM order_details 
      GROUP BY product_id 
     ) s ON s.product_id = p.product_id 
WHERE p.department_id = :department_id 
     AND p.is_active = 1 
$orderby 
LIMIT :limit OFFSET :offset 

或這個怎麼樣,(您當前的查詢

COALESCE((SELECT COUNT(*) 
      FROM order_details od 
      WHERE od.product_id = p.product_id), 0) as most_popular 
+0

我沒有得到記錄和錯誤,但它說調用成員函數fetchColumn()在非對象 – ONYX 2013-04-30 03:31:13

+0

你是第二次嘗試工作我不知道爲什麼它在我編寫相同的代碼時沒有用,但是在聲明開始時和結束時沒有括號。你需要在開始和結束括號。例如COALESCE((SELECT ....),0)而不是COALESCE(SELECT ....,) – ONYX 2013-04-30 03:37:34

+0

我想早點上你,但是你刪除了它!這只是因爲一個小提琴。 http://sqlfiddle.com/#!2/77842/1 – 2013-04-30 03:43:49