简体   繁体   中英

SQL query to replace unmatching or null with a zero count

I have a query that is design to return a static list of subcategories(sid) for a given category by zone(zid). Next to the subcategory name I need a count of businesses (bid) matching the subcategory in that zone. (ex. places (3) ) It works unless another zone has a business for the subcategory then the query doesn't recognize this as null or zero. What is the best way to rewrite this so that it returns all subcategories and counts if the value exists only for that zone or else returns (0)

<?php
ob_start();  
$sql = "Select COUNT(b.name)as cnt, s.name,s.sid, b.zid from subcategory s left JOIN business b on s.sid = b.sid where s.cid = '10' and b.zid is null or b.zid ='1'and s.cid = '10' group by s.sid ORDER BY s.name ";

$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
                                 
if ($queryResults > 0) { while ($row = mysqli_fetch_array($result)) 
{echo 
"<div class='pcat_list'><a href='subcategory.php?ID={$row['sid']}&ZONE=1' style='color:#444'>".$row['name']."(".$row['cnt'].")</a></div>";
}
}

You can use the mysql Function "IFNULL"

Select IFNULL(COUNT(b.name), 0) as cnt, s.name,s.sid, IFNULL(b.zid, 0)
from subcategory s
left JOIN business b on s.sid = b.sid 
where s.cid = '10' and b.zid is null or b.zid ='1'and s.cid = '10' group by s.sid ORDER BY s.name

This is going to replace the null values with 0.

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