Compare only day and month with date field in mysql

前端 未结 4 435
慢半拍i
慢半拍i 2020-11-30 07:16

How to compare only day and month with date field in mysql? For example, I\'ve a date in one table: 2014-07-10

Similarly, another date 2000-07-10<

相关标签:
4条回答
  • 2020-11-30 07:26

    you can do it with the DAYOFMONTH and MONTH function:

    SELECT *
    FROM table
    WHERE DAYOFMONTH(field) = 31 AND MONTH(field) = 12 AND id = 1;
    

    EDIT: Of course you can write following too if you want to compare two fields:

    SELECT *
    FROM table
    WHERE 
        DAYOFMONTH(field) = DAYOFMONTH(field2) 
        AND MONTH(field) = MONTH(field2) 
        AND id = 1 ...;
    

    for further information have a look at the manual:

    1. MONTH
    2. DAYOFMONTH
    0 讨论(0)
  • 2020-11-30 07:31

    Use DATE_FORMAT instead:

    SELECT DATE_FORMAT('2000-07-10','%m-%d')
    

    yields

    07-10
    

    Here's your query re-written with DATE_FORMAT():

    SELECT *
    FROM table
    WHERE DATE_FORMAT(field, '%m-%d') = DATE_FORMAT('2000-07-10', '%m-%d')
    AND id = "1"
    
    0 讨论(0)
  • 2020-11-30 07:45

    Use MONTH and DAY functions:

    Try this:

    SELECT *
    FROM tableA a 
    WHERE a.id = 1 AND MONTH(a.field) = MONTH('2000-07-10') AND 
          DAY(a.field) = DAY('2000-07-10') 
    
    0 讨论(0)
  • 2020-11-30 07:51

    You could use DATE_FORMAT:

    SELECT * FROM `table`
        WHERE DATE_FORMAT(STR_TO_DATE(`field`, '%Y-%m-%d'), '%d-%m') = DATE_FORMAT(STR_TO_DATE('2000-07-10','%Y-%m-%d'), '%d-%m')
    

    also the second WHERE is not valid. Anyway you would want to get all rows not only id=1

    0 讨论(0)
提交回复
热议问题