MySQL select rows with date like

后端 未结 6 1922
刺人心
刺人心 2020-12-10 12:31

In MySQL I have this query

SELECT DISTINCT date, descr FROM book ORDER BY date

Date is in format yyyy-mm-dd

I want to

相关标签:
6条回答
  • 2020-12-10 12:32

    You can use >= and <= operators here. Check the below code:

    SELECT *
    FROM book
    WHERE date >= '2012-01-01' AND date <= '2012-01-31'
    
    0 讨论(0)
  • 2020-12-10 12:35
    SELECT DISTINCT date, descr
    FROM book
    WHERE YEAR = DATE(NOW()) AND MONTH(date) = '1'
    

    This will give you this years books

    0 讨论(0)
  • 2020-12-10 12:38

    If you are adamant that you want to use the LIKE syntax, you can convert the date to CHAR first:

    SELECT DISTINCT date, descr FROM book WHERE CAST(date AS char) LIKE '2012-01%' ORDER BY date;

    0 讨论(0)
  • 2020-12-10 12:51

    Using DATE_FORMAT function

    SELECT DISTINCT date, descr FROM book 
    WHERE DATE_FORMAT(date, '%Y %m') = DATE_FORMAT('2012-01-01', '%Y %m')
    ORDER BY date
    

    Or using MONTH and YEAR functions

    SELECT DISTINCT date, descr FROM book 
    WHERE Month(date) = Month('2012-01-01')
    AND Year(date) = Year('2012-01-01')
    ORDER BY date;
    

    Or using BETWEEN functions

    SELECT DISTINCT date, descr FROM book 
    WHERE date BETWEEN '2012-01-01'
    AND '2012-01-31'
    ORDER BY date;
    

    Or using <= and >= operators

    SELECT DISTINCT date, descr FROM book 
    WHERE date >= '2012-01-01'
    AND date <= '2012-01-31'
    ORDER BY date;
    

    See this SQLFiddle

    0 讨论(0)
  • 2020-12-10 12:51

    Try this:

    SELECT DISTINCT date, descr FROM book WHERE YEAR(date) = '2012' and MONTH(date) = '1'
    

    This works if your "date"-column is a MySQL date field.

    0 讨论(0)
  • 2020-12-10 12:59

    Using like also works. With @hims056 fiddle, you can test it:

    SELECT DISTINCT ID, date FROM book 
    WHERE date LIKE '2012-01%'
    ORDER BY date;
    

    However, it's not usual to use a like for date filtering, for me it's more natural to use >= and <= , or between. Also, there's a performance benefit.

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