Programing

mysql 쿼리의 if 조건으로 계산

lottogame 2020. 8. 22. 11:27
반응형

mysql 쿼리의 if 조건으로 계산


두 개의 테이블이 있는데 하나는 뉴스 용이고 다른 하나는 댓글 용이며 상태가 승인 됨으로 설정된 댓글 수를 가져오고 싶습니다.

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 

그러나이 쿼리의 문제점은 해당 뉴스에 해당하는 댓글이 있는지 여부에 관계없이 댓글 열에 대해 가져 오는 최소값이 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의 부울 유형이 C에서 INT 0같이 로 표시되기 때문에 작동합니다 1. (하지만 DB 시스템간에 이식 할 수는 없습니다.)

에 관해서는 COALESCE()다른 답변에서 언급 한 바와 같이, 많은 언어 API는 자동으로 변환 NULL''값을 가져올 때. 예를 들어 PHP의 mysqli인터페이스를 사용하면 COALESCE().


이것은 작동합니다.

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

count()값이 존재하는지 여부 만 확인하십시오. 0은 존재하는 값과 동일하므로 하나 더 세고 NULL은 존재하지 않는 값과 같으므로 계산되지 않습니다.


다음 줄을 바꿉니다.

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

이것으로 :

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

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

반응형