http://sqlfiddle.com/#!9/406cb/2
我有一本分类为1、2、3、4的餐桌书。
如何编写查询以获得所需的结果?
例如:
unix_time
很快..
桌子:
CREATE TABLE `books` ( `id` int(255) NOT NULL AUTO_INCREMENT, `name` longtext NOT NULL, `category` varchar(255) NOT NULL, `unix_time` bigint(20) NOT NULL, `time_data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ; INSERT INTO `books` (`id`, `name`, `category`, `unix_time`, `time_data`) VALUES (1, 'book1', '1', 1454411248, '2016-02-02 05:37:28'), (2, 'book2', '2', 1454411248, '2016-02-02 05:37:28'), (3, 'book3', '3', 1454411248, '2016-02-02 05:37:28'), (4, 'book4', '4', 1454411248, '2016-02-02 05:37:28'), (5, 'book5', '1', 1454411248, '2016-02-02 05:37:28'), (6, 'book6', '2', 1454411248, '2016-02-02 05:37:28'), (7, 'book7', '3', 1454411248, '2016-02-02 05:37:28'), (8, 'book8', '4', 1454411248, '2016-02-02 05:37:28'), (9, 'book9', '1', 1454497648, '2016-02-03 05:37:28'), (10, 'book10', '2', 1454497648, '2016-02-03 05:37:28'), (11, 'book11', '1', 1454497648, '2016-02-03 05:37:28'), (12, 'book12', '2', 1454497648, '2016-02-03 05:37:28'), (13, 'book13', '3', 1454497648, '2016-02-03 05:37:28'), (14, 'book14', '4', 1454497648, '2016-02-03 05:37:28'), (15, 'book15', '1', 1454497648, '2016-02-03 05:37:28'), (16, 'book16', '2', 1454497648, '2016-02-03 05:37:28'), (17, 'book17', '3', 1454497648, '2016-02-03 05:37:28'), (18, 'book18', '4', 1454497648, '2016-02-03 05:37:28');
询问:
SELECT *, CASE category WHEN '1' THEN '1454407648' WHEN '2' THEN '1454404048' WHEN '3' THEN '1454396848' WHEN '4' THEN '1454389648' END as category from books where unix_time >1454411248
首先,您需要一个表格将您的category价值观与价值观联系起来duration。您可以创建一个物理表,也可以使用这样的子查询来生成一个虚拟表。
category
duration
select 1 as category, 1 as duration UNION ALL select 2,2 UNION ALL select 3,4 UNION ALL select 4,6
这将产生以下的小查询表。
|| *category* || *duration* || || 1 || 1 || || 2 || 2 || || 3 || 4 || || 4 || 6 ||
接下来,您需要books像这样将查找表加入到您的表中。该查询还可以包括一expiration列,如图所示。
books
expiration
select b.*, d.duration, FROM_UNIXTIME(unix_time) + INTERVAL d.duration HOUR expiration from books b join (select 1 as category, 1 as duration UNION ALL select 2,2 UNION ALL select 3,4 UNION ALL select 4,6 ) d ON b.category = d.category
最后,您添加一个WHERE子句以过滤出未到期的行。
WHERE
select b.*, d.duration, FROM_UNIXTIME(unix_time) + INTERVAL d.duration HOUR expiration from books b join (select 1 as category, 1 as duration UNION ALL select 2,2 UNION ALL select 3,4 UNION ALL select 4,6 ) d ON b.category = d.category where FROM_UNIXTIME(unix_time) + INTERVAL d.duration HOUR >= '2016-02-03 08:00:00'
在此示例中,我将其2016-02-03 08:00:00用作当前时间。您可以在生产系统中使用NOW()。
2016-02-03 08:00:00
NOW()
您也可以使用该子句的可扩展版本where。
where
where unix_time >= UNIX_TIMESTAMP('2016-02-03 08:00:00' - INTERVAL d.duration HOUR)
最后,这是一种设计偏好,但是混合DATETIME和unix时间戳列有点奇怪。
DATETIME