简体   繁体   中英

MYSQL COUNT return NULL?

I have googled my problem but didnt get the answer. I want to list all of the results of below sql including NULL (when COUNT(review.id) return 0 also) but instead i just got the results of articles of place that only contains review.

$sql = "SELECT tbl_place.id, tbl_place.region_id, tbl_place.subregion_id, tbl_place.title, tbl_place.metalink, tbl_place.img_thumbnail, tbl_place.summary, tbl_place.category1_id, tbl_place.category2_id, tbl_place.category3_id, COUNT(review.id) AS total_review FROM tbl_place
        JOIN review ON tbl_place.id = review.place_id
        WHERE
        tbl_place.category1_id = '32'   AND 
        tbl_place.status = '1'          AND
        review.rating != '0.00'         
        GROUP BY tbl_place.id
        ORDER BY total_review $by
        LIMIT $limit OFFSET $offset";

please use left join for review table instead of join. join is by default inner join so it will take only matched records.

the sql should be :

$sql = "SELECT tbl_place.id, 
tbl_place.region_id, 
tbl_place.subregion_id, 
tbl_place.title, 
tbl_place.metalink, 
tbl_place.img_thumbnail, 
tbl_place.summary, 
tbl_place.category1_id, 
tbl_place.category2_id, 
tbl_place.category3_id, 
(SELECT COUNT(*) FROM review WHERE review.rating != '0.00' AND tbl_place.id = review.place_id ) AS total_review 
FROM tbl_place WHERE 
tbl_place.category1_id = '32' AND 
tbl_place.status = '1'   
GROUP BY tbl_place.id 
ORDER BY total_review $by";

it's working! thx guys!

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