在我的博客上,我想显示上个月的所有帖子.但如果这不到10个帖子,我想显示最近的10个帖子(换句话说,首页上的帖子永远不应少于10个).我想知道是否有办法在单个查询中执行此操作?
目前,我首先运行此查询:
select count(*) from posts where timestamp > ($thirty_days_ago)
order by timestamp desc
Run Code Online (Sandbox Code Playgroud)
如果该计数大于或等于10:
select * from posts where timestamp > ($thirty_days_ago)
order by timestamp desc
Run Code Online (Sandbox Code Playgroud)
除此以外:
select * from posts order by timestamp desc limit 10
Run Code Online (Sandbox Code Playgroud)
但是这需要我运行两个查询.使用单个查询有更有效的方法吗?(我正在使用MySQL.)
(SELECT * FROM posts
WHERE `timestamp` >= NOW() - INTERVAL 30 DAY)
UNION
(SELECT * FROM posts
ORDER BY `timestamp` DESC
LIMIT 10);
Run Code Online (Sandbox Code Playgroud)
编辑: Re @ doofledorfer的评论:我在我的测试数据库上运行它,它运行正常.我尝试比较timestamp
日期文字以及上面查询中显示的常量表达式,但它对优化计划没有任何影响.当然,我使用了大量的数据,如果有数千行,优化计划可能会有所不同.
在任何情况下,OP都在询问如何在单个查询中获得正确的结果,而不是如何使执行计划达到最佳.毕竟这是一个UNION查询,并且必然会产生一个文件排序.
+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
| 1 | PRIMARY | posts | ALL | timestamp | NULL | NULL | NULL | 20 | Using where |
| 2 | UNION | posts | ALL | NULL | NULL | NULL | NULL | 20 | Using filesort |
| NULL | UNION RESULT | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | |
+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1330 次 |
最近记录: |