如何选择比一周更新的行?

问题描述 投票:1回答:1

使用MariaDB 10,我想查询article表中过去一周的文章:

这是我的查询:

SELECT * FROM article WHERE category="News" AND created_at < NOW() - INTERVAL 1 WEEK ORDER BY created_at DESC;

但它会返回所有文章。

解释文章;

+-------------+-----------------+------+-----+-------------------+----------------+
| Field       | Type            | Null | Key | Default           | Extra          |
+-------------+-----------------+------+-----+-------------------+----------------+
| id          | int(6) unsigned | NO   | PRI | NULL              | auto_increment |
| title       | varchar(150)    | NO   |     | NULL              |                |
| content     | mediumtext      | NO   |     | NULL              |                |
| created_at  | timestamp       | NO   |     | CURRENT_TIMESTAMP |                |
| category    | varchar(64)     | NO   |     | test              |                |

我怎样才能做到这一点?

mysql sql mariadb intervals
1个回答
2
投票

逻辑是倒退的。你想要>而不是<

SELECT a.*
FROM article a
WHERE category = 'News' AND
      created_at > NOW() - INTERVAL 1 WEEK
ORDER BY created_at DESC;

为了提高性能,你需要一个关于article(category, created_at)的索引。

© www.soinside.com 2019 - 2024. All rights reserved.