2014-09-20 119 views
0

我使用下面的查詢和用PHP編寫的子查詢。發生如果一個子查詢爲空,則Mysql查詢返回空值

$query = mysqli_query($mysqli, "select 
     users.id as id, 
     users.display_name as display_name, 
     users.user_code as user_code, 
     (select count(articles.id) from articles where articles.user_code = '$user_code') as user_article_count, 
     (select count(comments.id) from comments where comments.user_code = '$user_code') as user_comment_count 
     from users"); 

我的問題,只要子查詢的一個不匹配任何行,整個查詢返回空值,而不是返回null只是user_article_countuser_comment_count

我該如何避免這種情況?

回答

0

MS SQL有同樣的問題,我使用ISNULL()函數解決它。 您是否嘗試過MYSQL中的IFNULL()函數?

我在http://www.w3schools.com/sql/sql_isnull.asp找到了這個片段。

在MySQL中,你可以使用IFNULL()函數,就像這樣:

SELECT產品名稱,單價*(庫存量+ IFNULL(UnitsOnOrder,0)) 產品來自

HTH, 喬