MySQL Where date is greater than one month?

前端 未结 3 1990
南笙
南笙 2021-01-17 10:24

I have a datetime column called \'last_login\'.

I want to query my database to select all records that haven\'t logged in within the last month. How do I do this?

相关标签:
3条回答
  • 2021-01-17 10:50

    Try using date_sub

    where u.last_login < date_sub(now(), interval 1 month)
    

    (Similar to the first answer but in my mind it is more "natural" to use positive integers)

    0 讨论(0)
  • 2021-01-17 11:14

    matthewh was almost correct, except the > should have been a right one.

    where u.last_login > date_sub(now(), interval 1 month)

    0 讨论(0)
  • 2021-01-17 11:16

    You can use date_add combined with now:

    ...where u.last_login < date_add(now(), interval -1 month)
    

    Naturally, as both are MySQL-specific this limits you to MySQL backends. Alternately, you can figure out what the date was a month ago with PHP (I'm not a PHP person, but I'm guessing DateTime::sub would help with that) and then include that date in your query in the normal way you would any other date/time field.

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