hongsgo avatar

mysql problems-with-null

hongsgo

Published: 04 May 2018 › Updated: 04 May 2018mysql problems-with-null

mysql problems-with-null

Mysql에 마이그레이션에 대한 검증 쿼리를 만들다가 null값 조건 사용과 관련하여 미처 몰랐던 내용을 알게되어 공유 드립니다.

질문 : 아래 A/B의 SELECT 결과 값은 무엇 일까요
A. SELECT IF(NULL != 11, ‘True’, ‘False’);
B. SELECT IF(NULL != NULL , ‘True’, ‘False’);

  1. 결과
    A. false
    B. false

  2. 이유를 찾아 보니..
    To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression
    http://dev.mysql.com/doc/refman/5.6/en/working-with-null.html
    http://dev.mysql.com/doc/refman/5.6/en/problems-with-null.html
    http://stackoverflow.com/questions/3536670/mysql-selecting-rows-where-a-column-is-null
    ….

  3. 원래 하고 싶던 일.
    아래 쿼리를 수행하여, bl에 event_template_no가 11이 아닌 경우를 모두 찾아,
    카운팅 하고 싶었음(실제로 105,106번 mt.ticket_no 의 결과에서는 bl.event_template_no가 모두 null값인 Row가 755490건이 존재함)
    수행했던 Query 예)
    SELECT COUNT(*)
    FROM table_a AS mt INNER JOIN table_b AS bl ON mt.table_b_no=bl.table_b_no
    WHERE mt.ticket_no IN(105,106)
    AND bl.event_template_no != 11
    수행 결과 = 0

  4. 상기 3번의 내용을 참고해서 query 수정
    A. OR 연산 사용
    SELECT COUNT()
    FROM table_a AS mt INNER JOIN table_b AS bl ON mt.table_b_no=bl.table_b_no
    WHERE mt.ticket_no IN(105,106)
    AND bl.event_template_no != 11 OR bl.event_template_no IS NULL
    — 결과 잘 나옴.
    B. IFNULL 사용.
    SELECT COUNT(
    )
    FROM table_a AS mt INNER JOIN table_b AS bl ON mt.table_b_no=bl.table_b_no
    WHERE mt.ticket_no IN(105,106)
    AND IFNULL(bl.event_template_no,0) != 11

Leave mysql problems-with-null to:

Written by

Read more #mysql posts


Best Posts From hongsgo

We have not curated any of hongsgo's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From hongsgo