Mysql SQL将时间线中的类别联接到时间戳表中
考虑以下结构:Mysql SQL将时间线中的类别联接到时间戳表中,mysql,sql,join,Mysql,Sql,Join,考虑以下结构: create table timestamps(id int, stamp timestamp); insert into timestamps values (1,'2017-10-01 10:05:01'), (2,'2017-10-01 11:05:01'), (3,'2017-10-01 12:05:01'), (4,'2017-10-01 13:05:01'); create table category_timeline(begin timestamp,end ti
create table timestamps(id int, stamp timestamp);
insert into timestamps values
(1,'2017-10-01 10:05:01'),
(2,'2017-10-01 11:05:01'),
(3,'2017-10-01 12:05:01'),
(4,'2017-10-01 13:05:01');
create table category_timeline(begin timestamp,end timestamp, category varchar(100));
insert into category_timeline values
('2017-10-01 10:01:03','2017-10-01 12:01:03','Cat1'),
('2017-10-01 12:01:03','2017-10-01 12:42:43','Cat3'),
('2017-10-01 12:42:43','2017-10-01 14:01:03','Cat2');
Sqlfiddle相同:
我有两个表,一个(timestamps
)包含时间戳,另一个(category\u timeline
)包含类别时间线,也就是说,我们假设category\u timeline
中的记录形成一个连续的非重叠时间线,为每个时间段分配一个类别
我想将类别分配给时间戳
表,结果是:
| id | stamp | category |
|----|----------------------|----------|
| 1 | 2017-10-01T10:05:01Z | Cat1 |
| 2 | 2017-10-01T11:05:01Z | Cat1 |
| 3 | 2017-10-01T12:05:01Z | Cat3 |
| 4 | 2017-10-01T13:05:01Z | Cat2 |
这是以下查询的结果:
SELECT id, stamp, category FROM timestamps ts
LEFT JOIN category_timeline tl
ON ts.stamp >= tl.begin
AND ts.stamp < tl.end
从时间戳ts中选择id、stamp、category
左连接类别\u时间线tl
在ts.stamp>=tl.begin上
和ts.stamp
然而,一旦表格变大,此操作似乎会以指数级速度变慢,是否有更好的方法来实现这一点,假设任何时间戳只在另一个表格中的唯一时间段内。我建议采用这种方法:
SELECT ts.id, ts.stamp,
(SELECT tl.category
FROM category_timeline tl
WHERE tl.end > ts.stamp
ORDER BY tl.end ASC
LIMIT 1
) as category
FROM timestamps ts ;
确保在类别\时间轴(结束,类别)
上有索引