我希望选择并将未来和之前事件的数量限制为20,例如,首先是最新事件。
future_events
和previous_event
是1或0.如果需要,我可以存储为单个列。
我想我错过了一个GROUP BY,但今天早上我的大脑却没有。这就是我所拥有的:
SELECT name, start_timestamp, end_timestamp, future_event, previous_event, url
FROM events_table
WHERE status != 'draft' AND status != 'canceled'
-- AND SUM(previous_event) <= 20
-- AND SUM(future_event) <= 20
ORDER BY start_timestamp DESC
-- Sample Table
CREATE TABLE IF NOT EXISTS `events_table` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`url` varchar(500) NOT NULL,
`start_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`end_timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` varchar(10) NOT NULL,
`future_event` tinyint(1) NOT NULL,
`previous_event` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
-- Data
-- Each row is an event with a unique event, time, url etc.
预期结果
future_event
= 1)previous_event
= 1)答案 0 :(得分:0)
您可以按照以下方式使用 -
SELECT a.* FROM ((SELECT `name`, start_timestamp, end_timestamp, future_event, previous_event, url
FROM events_table
WHERE STATUS != 'draft' AND STATUS != 'canceled' AND previous_event = 1
ORDER BY start_timestamp DESC LIMIT 20)
UNION
(SELECT `name`, start_timestamp, end_timestamp, future_event, previous_event, url
FROM events_table
WHERE STATUS != 'draft' AND STATUS != 'canceled' AND previous_event = 1
ORDER BY start_timestamp DESC LIMIT 20)) a ORDER BY start_timestamp DESC;
答案 1 :(得分:0)
您可以使用UNION并执行两项请求:
((SELECT `name`,
start_timestamp,
end_timestamp,
future_event,
previous_event, url
FROM events_table
WHERE STATUS != 'draft'
AND STATUS != 'canceled'
and future_event = 1
ORDER BY start_timestamp DESC limit 20)
UNION
(SELECT `name`,
start_timestamp,
end_timestamp,
future_event,
previous_event,
url
FROM events_table
WHERE STATUS != 'draft'
AND STATUS != 'canceled'
and previous_event = 1
ORDER BY start_timestamp DESC limit 20))