programing

MySQL: 여러 열의 MAX 또는 GREAST를 가져오지만 NULL 필드를 사용합니다.

firstcheck 2022. 10. 28. 21:12
반응형

MySQL: 여러 열의 MAX 또는 GREAST를 가져오지만 NULL 필드를 사용합니다.

각 레코드(MySQL)의 3개의 다른 필드에서 최대 날짜를 선택하려고 합니다.각 행에는 date1, date2 및 date3이 있습니다.date1은 항상 채워져 있습니다.date2 및 date3은 NULL이 될 수 있습니다.GREATE 문장은 단순하고 간결하지만 NULL 필드에는 영향을 주지 않습니다.

SELECT id, GREATEST(date1, date2, date3) as datemax FROM mytable

또, 다음과 같은 보다 복잡한 솔루션도 시험해 보았습니다.

SELECT
    CASE
        WHEN date1 >= date2 AND date1 >= date3 THEN date1
        WHEN date2 >= date1 AND date2 >= date3 THEN date2
        WHEN date3 >= date1 AND date3 >= date2 THEN date3
        ELSE                                        date1
    END AS MostRecentDate

여기서도 마찬가지입니다.NULL 값은 올바른 레코드를 반환할 때 큰 문제입니다.

제발, 해결책이 있나요?잘 부탁드립니다.

사용하다COALESCE

SELECT id, 
   GREATEST(date1, 
     COALESCE(date2, 0),
     COALESCE(date3, 0)) as datemax 
FROM mytable

업데이트: 이 답변은 이전에 사용되었습니다.IFNULL하지만 마이크 체임벌린이 댓글에서 지적했듯이COALESCE실제로는 권장되는 방법입니다.

한다면date1있을 수 없다NULL, 그러면 결과는 결코 다음과 같을 수 없습니다.NULL,그렇죠?그럼 이걸 쓰셔도 돼요NULL날짜는 계산에 포함되지 않습니다(또는 변경).1000-01-01로.9999-12-31Null을 "시간 종료"로 카운트하는 경우:

GREATEST( date1
        , COALESCE(date2, '1000-01-01')
        , COALESCE(date3, '1000-01-01')
        ) AS datemax

COALESCE날짜 컬럼을 사용하기 전에GREATEST.

그것들을 처리하는 방법은 당신이 어떻게 대처하고 싶은가에 따라 달라집니다.NULL높거나 낮거나?

만약 모든 날짜가 무효가 된다면요?출력으로 null을 사용하고 싶은 거죠?그럼 이게 필요하겠네

select nullif(greatest(coalesce(<DATEA>, from_unixtime(0)), coalesce(<DATEB>, from_unixtime(0))), from_unixtime(0));

둘 다 null이면 null이 되고 둘 중 하나가 null이 아닌 경우에는 null이 됩니다.

특히 여러 번 사용하는 경우에는 다음과 같이 함수로 작성할 수 있습니다.

delimiter //
drop function if exists cp_greatest_date//
create function cp_greatest_date ( dateA timestamp, dateB timestamp ) returns timestamp
  deterministic reads sql data
  begin

    # if both are null you get null, if one of them is not null of both of them are not null, you get the greatest
    set @output = nullif(greatest(coalesce(dateA, from_unixtime(0)), coalesce(dateB, from_unixtime(0))), from_unixtime(0));
    # santiago arizti

    return @output;
  end //
delimiter ;

그럼 이렇게 쓰시면 됩니다.

select cp_greatest_date(current_timestamp, null);
-- output is 2017-05-05 20:22:45

언급URL : https://stackoverflow.com/questions/9831851/mysql-get-max-or-greatest-of-several-columns-but-with-null-fields

반응형