programing

MySQL 쿼리의 IF 조건으로 카운트

coolbiz 2022. 9. 24. 23:29
반응형

MySQL 쿼리의 IF 조건으로 카운트

2개의 테이블이 있습니다.하나는 뉴스용 테이블이고 다른 하나는 댓글용 테이블입니다.승인된 상태로 설정된 댓글 수를 알고 싶습니다.

SELECT
    ccc_news . *, 
    count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 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 

그러나 이 쿼리의 문제는 해당 뉴스에 대응하는 코멘트가 존재하는지 여부에 관계없이 comments 열에 대해 취득되는 최소값이 1이라는 것입니다.

어떤 도움이라도 주시면 대단히 감사하겠습니다.

사용하다sum()대신해서count()

아래 시도:

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 

더 나은(또는 더 짧은):

SUM(ccc_news_comments.id = 'approved')

MySQL의 Boolean 타입은 다음과 같이 표시되므로 이 기능이 작동합니다.INT 0그리고.1(단, DB 시스템 간에 이식할 수 없는 경우도 있습니다.

에 대해서는COALESCE()다른 답변에서 언급했듯이, 많은 언어 API는 자동으로 변환됩니다.NULL로.''값을 가져올 때 사용합니다.예를 들어 PHP의 경우mysqli인터페이스 없이 쿼리를 실행하는 것이 안전합니다.COALESCE().

이 조작은 유효합니다.

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))

count()값이 존재하는지 여부만 확인합니다.0은 기존 값과 같기 때문에 1개 더 카운트됩니다.NULL은 존재하지 않는 값과 같기 때문에 카운트되지 않습니다.

다음 행을 바꿉니다.

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments

이것으로:

coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments
count(ccc_news_comments.id = 'approved' or null)

보다 간결하게

언급URL : https://stackoverflow.com/questions/9798937/count-with-if-condition-in-mysql-query

반응형