Home > Database > Mysql Tutorial > How Can I Correctly Count Approved Comments in MySQL to Avoid a Minimum of 1?

How Can I Correctly Count Approved Comments in MySQL to Avoid a Minimum of 1?

Barbara Streisand
Release: 2024-11-28 03:48:13
Original
924 people have browsed it

How Can I Correctly Count Approved Comments in MySQL to Avoid a Minimum of 1?

Solving Comment Count Issue with IF Condition in MySQL Query

You're facing an issue where your MySQL query consistently returns a minimum comment count of 1 even in the absence of approved comments for certain news articles. To rectify this, let's explore a revised approach.

Your query employs the count() function to tally approved comments, but it inherently yields a minimum value of 1 for every row, irrespective of comment existence. The solution lies in utilizing the sum() function instead.

Consider the following modified query:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20
Copy after login

In this revised version, we utilize the sum() function within the if() statement's conditional expression. It calculates the aggregate count of 1's for approved comments and 0's for unapproved comments, effectively returning an accurate tally of approved comments for each news article.

The above is the detailed content of How Can I Correctly Count Approved Comments in MySQL to Avoid a Minimum of 1?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template