有一个由~10列组成的表,如何选择时间戳是最新列的那些列的所有组合?
Country City Street ... Timestamp
Poland Warsaw OldSt ... 5/25/2018
Poland Warsaw NewSt ... 6/14/2018
Germany Berlin OldSt ... 5/30/2018
Germany Berlin NewSt ... 6/14/2018
France Paris SomeSt ... 6/14/2018
会得到我
Country City Street ... Timestamp
Poland Warsaw NewSt ... 6/14/2018
Germany Berlin NewSt ... 6/14/2018
France Paris SomeSt ... 6/14/2018
我相信有很多方法可以解决这个问题。但是效果最好的是什么?
表格的DDL:
-- auto-generated definition
create table SDATA
(
SID bigint unsigned auto_increment
primary key,
FG varchar(100) charset utf8 default '' not null,
COUNTRY varchar(100) charset utf8 default '' not null,
CITY varchar(100) charset utf8 default 'unknown' not null,
F_DATE date default '0000-00-00' not null,
INTERVAL_START datetime default '0000-00-00 00:00:00' not null,
INTERVAL_DURATION bigint unsigned default '0' not null,
VOLUME decimal(10, 5) default '0.00000' not null,
SNAPSHOT_DATE datetime default '0000-00-00 00:00:00' not null,
VERSION date null,
)
;
create index idx_SCD_IS_SD_FGN
on SDATA (INTERVAL_START, SNAPSHOT_DATE, FG);
虽然Gordon Linoff的回复有效,但它可以运行33秒,持续一周的数据。有什么方法可以加快速度吗?
答案 0 :(得分:4)
一种在数据库中运行良好的方法是相关子查询:
select t.*
from t
where t.timestamp = (select max(t2.timestamp)
from t t2
where t2.country = t.country and t2.city = t.city
);
为了提高性能,您需要(country, city, timestamp)
上的索引。
答案 1 :(得分:0)
试试这个
select *
from table
where timestamp = (select max(timestamp) from table)
修改
select *
from table a
where a.timestamp = (select max(timestamp) from table b where a.Country = b.country)
使用CTE编辑
with CTE
as
(
select COUNTRY, CITY, max(INTERVAL_START) as date from SDATA group by
COUNTRY, CITY
)
select a.* from SDATA as a
inner join CTE as b on a.COUNTRY = b.COUNTRY and a.CITY = b.CITY and a.INTERVAL_START = date