将 MYSQL 搜索结果限制为大于变量的日期

Limit MYSQL search results to dates greater than variable

我有一个 MYSQL table posts,其中包含一个 VARCHAR(25)created,其中填充了 XXXX-XX XX:XX:XX 格式的日期时间.我正在尝试按日期搜索 > 现在 - 24 小时。

//get the timestamp for now - 24 hours
$timeAgo=date("Y-m-d H:i:s", strtotime('-24 hours'));
//outputs something like 2020-09-17 12:32:44

//search for all posts that meet the criteria
$sql = "SELECT posts.*
        FROM posts
        WHERE posts.uuid='uuid1' 
        OR posts.uuid='uuid2' 
        OR posts.uuid='uuid3'
        AND posts.created > '$timeAgo'
        ORDER BY posts.id DESC
        ";

当仅使用一个 posts.uuid 进行搜索时,我得到了想要的结果,其中列出了过去 24 小时(或其他指定时间)内来自该 uuid 的所有帖子。

当我使用上面代码块中引用的多个 uuid 进行搜索时,我得到了不需要的结果,其中列出了来自各个 uuid 的所有帖子,无论它们是何时创建的。

如何使用多个 posts.uuid 搜索过去 24 小时(或其他指定时间)内的所有帖子?

OR 条件需要括号:

WHERE 
    (posts.uuid='uuid1' OR posts.uuid='uuid2' OR posts.uuid='uuid3')
    AND posts.created > '$timeAgo'

基本原理:AND 的优先级高于 OR,因此不带括号的表达式等同于:

WHERE 
    posts.uuid='uuid1' 
    OR posts.uuid='uuid2' 
    OR (posts.uuid='uuid3' AND posts.created > '$timeAgo')

使用更简单IN:

WHERE posts.uuid in ('uuid1', 'uuid2', 'uuid3') AND posts.created > '$timeAgo'

请注意,您可以直接在查询中而不是在 PHP 中计算日期。此外,您不需要在列前加上 table 名称前缀,因为查询中只涉及一个 table。我会这样表述:

SELECT *
FROM posts
WHERE uuid IN ('uuid1', 'uuid2', 'uuid3') AND created > now() - interval 1 day
ORDER BY id DESC