是否可以将日期(“Y-m-d H:i:s”)与mysqli_query中的time()进行比较?
问题描述:
I would like to select from database 10 most popular posts posted in last 24 hours based on likes. In database for each post I stored time when the post was posted using date("Y-m-d H:i:s") in column post_date.
I need something like this:
$most_popular = mysqli_query($mysqli_connect, "SELECT * FROM posts WHERE (time() - post_date) < 86400 ORDER BY likes DESC LIMIT 10");
答
you can do following:
SELECT *
FROM posts
WHERE post_date > DATE_SUB(NOW(), INTERVAL 1 DAY)
ORDER BY likes DESC
LIMIT 10
答
SELECT *
FROM posts
WHERE post_date >= (now() - INTERVAL 1 DAY)
ORDER BY ...
etc...
答
I would just compare the post_date
with 24 hours before:
$last_24_hours = date("Y-m-d H:i:s", strtotime("-24 Hours"));
$query = sprintf("SELECT *
FROM posts
WHERE post_date > '%s'
ORDER BY likes DESC
LIMIT 10", $last_24_hours);
$most_popular = mysqli_query($mysqli_connect, $query);
答
Your question is: "Is it possible to compare date (“Y-m-d H:i:s”) with time() inside mysqli_query?"
The answer is yes:
SELECT TIME('2003-12-31 01:02:03'); // returns '01:02:03'
NOTE: This CAN'T handle many dates, if that's your question.