我想仅在比现在早的时候按topped_time字段对mysql查询结果进行排序,例如,如果topped_time为2016-7-6,则应将其考虑在内,但如果topped_time为2016-7-16,则应将其忽略。
我试过了
SELECT * FROM `article` ORDER BY IF(`topped_time` < CURRENT_TIME(), '`topped_time` DESC', ''), `published_time` DESC
和
SELECT * FROM `article` ORDER BY CASE WHEN `topped_time=` < CURRENT_TIME() THEN `topped_time` END, `published_time` DESC
即使toptop_time仍然比现在晚。
表格如下:
CREATE TABLE `article` (
`id` bigint(20) UNSIGNED NOT NULL,
`published_time` datetime DEFAULT '0000-00-00 00:00:00',
`topped_time` datetime DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `article` (`id`, `published_time`, `topped_time`) VALUES
(1, '2016-07-05 22:01:14', '0000-00-00 00:00:00'),
(2, '2016-07-05 22:01:23', '0000-00-00 00:00:00'),
(3, '2016-07-05 22:01:25', '2016-07-07 00:00:00'),
(4, '2016-07-05 22:01:27', '0000-00-00 00:00:00'),
(5, '2016-07-05 22:01:29', '0000-00-00 00:00:00');
此屏幕快照中的正确顺序应为id:4,5,3,2,1,因为id 4的topped_time是2016-07-06 00:00:00,早于现在,应该是第一个。ID 3的topped_time是2016-07-07 00:00:00,并且比现在晚,应该忽略。
什么是正确的查询,还是不可能?
我想这是您的选择:
SELECT * FROM `article`
ORDER BY
IF (`topped_time` < NOW(), `topped_time`, '0000-00-00 00:00:00') DESC,
`published_time` DESC
+----+---------------------+---------------------+
| id | published_time | topped_time |
+----+---------------------+---------------------+
| 4 | 2016-07-05 22:01:27 | 2016-07-06 00:00:00 |
| 6 | 2016-07-05 22:01:28 | 2016-05-06 00:00:00 |
| 5 | 2016-07-05 22:01:29 | 0000-00-00 00:00:00 |
| 3 | 2016-07-05 22:01:25 | 2016-07-17 00:00:00 |
| 2 | 2016-07-05 22:01:23 | 0000-00-00 00:00:00 |
| 1 | 2016-07-05 22:01:14 | 0000-00-00 00:00:00 |
+----+---------------------+---------------------+
更新
您可能会注意到,我添加了另一行来证明您的解决方案是错误的
SELECT * FROM article
ORDER BY topped_time < CURRENT_TIME() AND
topped_time DESC, published_time DESC;
+----+---------------------+---------------------+
| id | published_time | topped_time |
+----+---------------------+---------------------+
| 6 | 2016-07-05 22:01:28 | 2016-05-06 00:00:00 |
| 4 | 2016-07-05 22:01:27 | 2016-07-06 00:00:00 |
| 5 | 2016-07-05 22:01:29 | 0000-00-00 00:00:00 |
| 3 | 2016-07-05 22:01:25 | 2016-07-17 00:00:00 |
| 2 | 2016-07-05 22:01:23 | 0000-00-00 00:00:00 |
| 1 | 2016-07-05 22:01:14 | 0000-00-00 00:00:00 |
+----+---------------------+---------------------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句