ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Mysql) Timestemp(데이터타입) 조회할때 날짜 비교하기
    Programing Study/E.T.C 2022. 1. 18. 14:29
    728x90
    반응형

    MySQL 내 date(), date_sub(), date_format() 함수를 활용한 Timestamp 날짜 비교

     

    1. 특정 날짜의 레코드 조회

    특정 날짜(ex, 2019-01-30)에 해당하는 레코드를 가져오기 위해...

    select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) = DATE('2019-01-30');

    위와 같이 사용할 수 있다.

    오늘 날짜로 비교하기 위해서 '2019-01-30' 대신 NOW()를 사용할 수도 있다.

     

    2. 지난 일주일 간의 레코드 조회

    >> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_SUB(NOW(), INTERVAL 7 DAY);

    DATE_SUB() 함수를 활용하여 사용할 수 있다.

    다른 기간의 자료를 조회하기 위해서 7 대신 필요한 만큼의 날짜수를 입력하면 된다.

     

    3. 이번 달에 등록된 레코드 조회

    >> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_FORMAT(NOW(), '%Y-%m-01');

    DATE_FORMAT() 함수를 활용하여 사용할 수 있다.

     

    4. 이번 년도에 등록된 레코드 조회

    >> select * from TABLE_NAME where DATE(TIMESTAMP_COLUMN) >= DATE_FORMAT(NOW(), '%Y-01-01');

     

    3번 항목과 크게 다르지 않다. 포맷 형식의 월에 대한 부분만 수정하면 된다.

     

    5. 참조자료 (https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html)

     

    ▷ DATE(expr)

    Extracts the date part of the date or datetime expression expr.

    mysql> SELECT DATE('2003-12-31 01:02:03');
            -> '2003-12-31'

     

    ▷ NOW([fsp])

    Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

    If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    mysql> SELECT NOW();
            -> '2007-12-15 23:50:26'
    mysql> SELECT NOW() + 0;
            -> 20071215235026.000000

    NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.

    mysql> SELECT NOW(), SLEEP(2), NOW();
    +---------------------+----------+---------------------+
    | NOW()               | SLEEP(2) | NOW()               |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
    +---------------------+----------+---------------------+
    
    mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
    +---------------------+----------+---------------------+
    | SYSDATE()           | SLEEP(2) | SYSDATE()           |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
    +---------------------+----------+---------------------+

    In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE(). Setting the timestamp to a nonzero value causes each subsequent invocation of NOW() to return that value. Setting the timestamp to zero cancels this effect so that NOW() once again returns the current date and time.

    See the description for SYSDATE() for additional information about the differences between the two functions.

     

    ▷ DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)

    These functions perform date arithmetic. The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is evaluated as a string; it may start with a - for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

    For more information about temporal interval syntax, including a full list of unit specifiers, the expected form of the expr argument for each unit value, and rules for operand interpretation in temporal arithmetic, see Temporal Intervals.

    The return value depends on the arguments:

    • DATE if the date argument is a DATE value and your calculations involve only YEAR, MONTH, and DAY parts (that is, no time parts).
    • DATETIME if the first argument is a DATETIME (or TIMESTAMP) value, or if the first argument is a DATE and the unit value uses HOURS, MINUTES, orSECONDS.
    • String otherwise.

    To ensure that the result is DATETIME, you can use CAST() to convert the first argument to DATETIME.

     
    mysql> SELECT DATE_ADD('2018-05-01',INTERVAL 1 DAY);
            -> '2018-05-02'
    mysql> SELECT DATE_SUB('2018-05-01',INTERVAL 1 YEAR);
            -> '2017-05-01'
    mysql> SELECT DATE_ADD('2020-12-31 23:59:59',
        ->                 INTERVAL 1 SECOND);
            -> '2021-01-01 00:00:00'
    mysql> SELECT DATE_ADD('2018-12-31 23:59:59',
        ->                 INTERVAL 1 DAY);
            -> '2019-01-01 23:59:59'
    mysql> SELECT DATE_ADD('2100-12-31 23:59:59',
        ->                 INTERVAL '1:1' MINUTE_SECOND);
            -> '2101-01-01 00:01:00'
    mysql> SELECT DATE_SUB('2025-01-01 00:00:00',
        ->                 INTERVAL '1 1:1:1' DAY_SECOND);
            -> '2024-12-30 22:58:59'
    mysql> SELECT DATE_ADD('1900-01-01 00:00:00',
        ->                 INTERVAL '-1 10' DAY_HOUR);
            -> '1899-12-30 14:00:00'
    mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
            -> '1997-12-02'
    mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002',
        ->            INTERVAL '1.999999' SECOND_MICROSECOND);
            -> '1993-01-01 00:00:01.000001'

     

    ▷ DATE_FORMAT(date,format)

    Formats the date value according to the format string.

    The following specifiers may be used in the format string. The % character is required before format specifier characters.

    SpecifierDescription
    %a Abbreviated weekday name (Sun..Sat)
    %b Abbreviated month name (Jan..Dec)
    %c Month, numeric (0..12)
    %D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
    %d Day of the month, numeric (00..31)
    %e Day of the month, numeric (0..31)
    %f Microseconds (000000..999999)
    %H Hour (00..23)
    %h Hour (01..12)
    %I Hour (01..12)
    %i Minutes, numeric (00..59)
    %j Day of year (001..366)
    %k Hour (0..23)
    %l Hour (1..12)
    %M Month name (January..December)
    %m Month, numeric (00..12)
    %p AM or PM
    %r Time, 12-hour (hh:mm:ss followed by AM or PM)
    %S Seconds (00..59)
    %s Seconds (00..59)
    %T Time, 24-hour (hh:mm:ss)
    %U Week (00..53), where Sunday is the first day of the week; WEEK() mode 0
    %u Week (00..53), where Monday is the first day of the week; WEEK() mode 1
    %V Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X
    %v Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x
    %W Weekday name (Sunday..Saturday)
    %w Day of the week (0=Sunday..6=Saturday)
    %X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
    %x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
    %Y Year, numeric, four digits
    %y Year, numeric (two digits)
    %% A literal % character
    %x x, for any x not listed above

    Ranges for the month and day specifiers begin with zero due to the fact that MySQL permits the storing of incomplete dates such as '2014-00-00'.

    The language used for day and month names and abbreviations is controlled by the value of the lc_time_names system variable (Section 10.15, “MySQL Server Locale Support”).

    For the %U, %u, %V, and %v specifiers, see the description of the WEEK() function for information about the mode values. The mode affects how week numbering occurs.

    DATE_FORMAT() returns a string with a character set and collation given by character_set_connection and collation_connection so that it can return month and weekday names containing non-ASCII characters.

     
    mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
            -> 'Sunday October 2009'
    mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
            -> '22:23:00'
    mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
        ->                 '%D %y %a %d %m %b %j');
            -> '4th 00 Thu 04 10 Oct 277'
    mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
        ->                 '%H %k %I %r %T %S %w');
            -> '22 22 10 10:23:00 PM 22:23:00 00 6'
    mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
            -> '1998 52'
    mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
            -> '00'

     

     

    도움되셨다면 하단의 광고 클릭 부탁드립니다 :)

    728x90
    반응형
Designed by Tistory.