我有一个带有性能数据表的mysql数据库。每个数据表条目都用于特定的计数器。
DATA
----
dat_date BIGINT
value BIGINT
dat_date DATETIME(3)
FK_dt_id BIGINT
对于每个条目,我需要计算速度和加速度。所以我想创建一个SELECT,它将选择一行PREVIOUS行。 FK_dt_id是计数器类型
的外键我试过这个:
SELECT d1.dat_date,
d1.value v1,
d1.PK_dat_id
FROM data d1
INNER JOIN (SELECT * FROM data d2 ORDER BY d2.dat_date) d2
ON (d2.dat_date < d1.dat_date
AND d2.FK_dt_id = d1.FK_dt_id)
它有效,但我无法获得以前的主键,只有它的价值。 有什么想法吗?
答案 0 :(得分:1)
使用用户变量的最简单(不是必要的最简单)方法(使用“纯粹的”MySQL语法)是一个小技巧:
select @pk_data_id as prev_pk_data_id
, @pk_data_id := (case
when @fk_counter_id = fk_counter_id then a.pk_data_id
else 0
end) as pk_data_id
, @fk_counter_id := a.fk_counter_id as fk_counter_id
from
(select @pk_data_id := 0, @fk_counter_id := 0) as init
, data as a
order by a.fk_counter_id, a.pk_data_id
获得此行集后,您可以将其与data
表格结合使用。
我将这个结果放在一个临时表中,稍后再使用它;像这样的东西:
drop table if exists temp_tbl;
create temporary table temp_tbl
select @pk_data_id as prev_pk_data_id
, @pk_data_id := (case
when @fk_counter_id = fk_counter_id then a.pk_data_id
else 0
end) as pk_data_id
, @fk_counter_id := a.fk_counter_id as fk_counter_id
from
(select @pk_data_id := 0, @fk_counter_id := 0) as init
, data as a
order by a.fk_counter_id, a.pk_data_id;
alter table temp_tbl
add index dId (pk_data_id),
add index pdId (prev_pk_data_id),
add index cId (fk_counter_id);
-- Now use the temp table to get what you need
select d1.*
, d2.pk_data_id as prev_pk_data_id
, d2.data_value as prev_data_value
, d2.data_datetime as prev_data_datetime
from data as d1
-- If you don't use the temp table, substitute 'temp_tbl' with
-- the query from above
inner join temp_tbl as a
on d1.pk_data_id = a.pk_data_id
and d1.fk_counter_id = a.fk_counter_id
left join data as d2
on a.prev_pk_data_id = d2.pk_data_id
and a.fk_counter_id = d2.fk_counter_id