简体   繁体   中英

SQL Convert date string to unix timestamp in query

I have a users table with a last_login column. This is an example of it's content for a user:

2014-06-30 14:53:14

I would like to return a list of my active users. an active user is one the logged in during the last 20 days.

My logic goes:

  1. Get 20 days ago's date in Unix timestamp: $twenty_days_ago = strtotime('20 days ago');
  2. Get all users where last_login > $twenty_days_ago

Is it possible to convert my last_login string to unix timestamp inside the sql code? without needing to return all users and looping through the array to check every single user row?

Somthing like: strtotime(last_login) > $twenty_days_ago

Thanks!

Yes, but...

For best shot at good performance, we prefer bare columns in predicates, and avoid wrapping columns in functions. (MySQL will not use an index range scan for columns wrapped in functions.

To enable an index range scan on the last_login column, we'd prefer a predicate of the form like this:

WHERE t.last_login > NOW() - INTERVAL 20 DAY

If what you are passing in as an argument is an integer unix timestamp, it would be better to convert that literal (one time) to match the datatype of the last_login column. MySQL provides the FROM_UNIXTIME() function that can perform this conversion. For example:

WHERE t.last_login > FROM_UNIXTIIME(1402416849) 

The answer to your question is "yes", it is possible to write a query in the form you asked. You could make use of the UNIX_TIMESTAMP function:

WHERE UNIX_TIMESTAMP(t.last_login) > 1402416849 

Again, as noted above, this approach disables MySQL's ability to use a range scan operation. This form forces MySQL to evaluate the UNIX_TIMESTAMP function for EVERY row in the table, and then compare the result to the literal.

When we do the conversion on the "literal" side, the conversion is done once, and we can reference the bare column in the predicate.

NOTE: Also be aware of timezone conversion issues, when the timezone of the client does not match the timezone of the server; the behavior may be unexpected, but it is well defined.

It sounds to me like what you really need is a select statement that will select based on the datetime column.

SELECT id FROM users WHERE last_login >= NOW() - INTERVAL 20 DAY

OR

try this article as a good starting point for converting between PHP UNIX timestamp and mySQL timestamp http://www.richardlord.net/blog/dates-in-php-and-mysql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM