简体   繁体   中英

Mysql query returns null if one subquery is null

I use following query with subqueries written in PHP.

$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");

My issue occurs whenever one of the subquery does not match any rows, the whole query returns null instead of returning null just for user_article_count or user_comment_count .

How do I avoid this?

MS SQL has the same issue and I get around it using the ISNULL() function. Have you tried the IFNULL() function in MYSQL?

I found this snippet at http://www.w3schools.com/sql/sql_isnull.asp .

In MySQL you can use the IFNULL() function, like this:

SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0)) FROM Products

HTH, Joe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM