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

时间:2018-03-02 17:57:35

标签: mysql sql mariadb intervals

使用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              |                |

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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)上的索引。