' start_date'字段的类型为' date'在我的表中如下所示:
CREATE TABLE `exhibition` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`intro` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`logo` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM AUTO_INCREMENT=37 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
我试图实现的是,今天是2月18日,查询列出所有按start_date升序排序的记录的结果如下:
record id 1 (start_date: Jan 3rd)
record id 2 (start_date: Feb 1st)
record id 3 (start_date: Feb 19th)
record id 4 (start_date: Mar 5th)
如何进行查询以便通过对start_date降序进行排序来列出记录(比今天更大),并将今天过去的最远记录移动到最后并堆叠如下:
record id 3 (start_date: Feb 19th)
record id 4 (start_date: Mar 5th)
<---- Feb 18th (today)
record id 1 (start_date: Jan 3rd) (46 days past today)
record id 2 (start_date: Feb 1st) (17 days past today)
我使用php并且请让我知道如果我应该使用php来实现这是mysql不能。如果是这样我怎么用PHP?
答案 0 :(得分:1)
您可以将查询分成两部分 - 一部分包含过去的所有日期和今天之前的一天 - 并添加一个额外的列,在今天之前和之后的几天内强制执行人工排序。 UNION
它会备份并按新列排序,然后按日期排序:
SELECT id, start_date, 1 AS extraOrderColumn
FROM exhibition
WHERE start_date >= NOW()
UNION ALL
SELECT id, start_date, 2 AS extraOrderColumn
FROM exhibition
WHERE start_date < NOW()
ORDER BY extraOrderColumn ASC, start_date ASC
答案 1 :(得分:0)
尝试
SELECT `id`, `start_date`
FROM `exhibition`
WHERE `start_date` >= NOW()
ORDER BY `start_date` desc
UNION ALL
SELECT `id`, `start_date`
FROM `exhibition`
WHERE `start_date` < NOW()
ORDER BY `start_date` asc;
或者如果您想要两个不同的查询:
//Greater than today
SELECT `id`, `start_date`
FROM `exhibition`
WHERE `start_date` >= NOW()
ORDER BY `start_date` desc;
//PAST TODAY
SELECT `id`, `start_date`
FROM `exhibition`
WHERE `start_date` < NOW()
ORDER BY `start_date` asc;