2014-09-20 118 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, 乔